这显然是正则表达式的工作,虽然我不知道你是否应该在练习中使用它们......
我将其发布为答案,以防万一。否则,请告诉我们...
#/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
编辑:
既然你不能使用正则表达式,我建议你改变思维方式......而不是检查字符是否属于有效的邮政编码,我建议你做相反的事情:检查它们是否不属于在有效的邮政编码中,一旦检测到错位(或错误)字符,就会返回 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(一旦您知道它无效,就没有必要继续检查,对吧?)