,這顯然是對正則表達式的工作,雖然我不知道你是否應該在鍛鍊使用它們...
我張貼此作爲一個答案就在你可以。否則,讓我們知道...
#/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(有上保持檢查是沒有意義的,一旦你知道它是不是有效的,對不對? )
你可以使用[replace()](http://docs.python.org/library/stdtypes.html?highlight=replace#str.replace) 'while循環呢。 *還有*,在某些情況下,你是否還想返回False? – Levon 2012-08-06 16:41:02
我要求返回真,如果真的是假,比它會返回假...我想... – Reginald 2012-08-06 16:46:40
'真'將永遠是真實的。 – 2012-08-06 16:53:53