Skip to main content
 首页 » 编程设计

python之验证邮政编码

2025年05月04日12mq0036

我正在做一些在线教程……我被困在一个练习中:定义一个函数 postalValidate(S),它首先检查 S 是否代表有效的邮政编码。 注意:我应该用字符串、列表、if 语句、循环和其他基本结构(如变量和函数)来解决它。

首先,删除所有空格; 余数必须是 L#L#L# 的形式,其中 L 是字母(小写或大写),# 是数字.

如果 S 不是有效的邮政编码,则返回 bool 值 False。如果 S 有效,则返回相同邮政编码的版本,格式为 L#L#L#,其中每个 L 都是大写。

我已经为这些练习创建了一个代码,但评分者说这是错误的,但我也会发布它。

def postalValidate(S): 
   while " " in S: 
     S.remove(" ") 
   for i in range(1,6,2): 
     S.isdigit(S[i]) 
   for j in range(0,5,2): 
     S.upper(S[j] 
     S.isalpha(S[j]) 
   return True 

请您参考如下方法:

这显然是正则表达式的工作,虽然我不知道你是否应该在练习中使用它们......

我将此作为答案发布,以防万一。否则,请告诉我们...

#/usr/bin/evn python 
 
import re 
zipCode = re.compile(r"\s*(\w\d\s*){3}\s*") 
 
if __name__ == "__main__": 
    samples = [ 
        "           44F 4 F", #Invalid 
        "  L0L0L0    ", #Valid 
        "  L0  L0  L0    ", #Valid 
    ] 
 
    for sample in samples: 
        if zipCode.match(sample): 
            print "The string %s is a valid zipCode (nice and clean: %s)" % (sample, sample.replace(" ", "").upper()) 
        else: 
            print "The string %s is NOT a valid zipCode" % sample 

编辑:

因为你不能使用正则表达式,我建议你改变思维方式...与其检查字符是否属于有效的邮政编码,我建议你做相反的事情:检查它们是否 DON 'T 属于有效的邮政编码,一旦检测到放错(或错误)的字符就返回 False:

def postalValidate(S): 
    S = S.upper().replace(" ", "") 
    if len(S) == 6: 
        for i in range(len(S)): 
            if i % 2 == 0: 
                #Even index (0, 2, 4, 6...) , has to be 'letter' 
                if not(S[i].isalpha()): 
                    return False  
            else: 
                #Odd index (1, 3, 5, 7...), must be 'number' 
                if not(S[i].isdigit()): 
                    return False 
 
    else: 
        #You can save some cpu ticks here... at this point, the string has to be of length 6 or you know it's not a zip 
        return False 
    return S 

return 语句停止当前函数的执行,所以一旦你意识到要检查的字符串有什么“错误”,你就可以返回 False(一旦你知道它无效就没有继续检查的意义了,对吧?)