我是一個Python新手,並想知道是否有人可以幫助檢查字符串的格式,例如郵政編碼,在特定點的字母和數字。是否有更有效的方法來檢查特定的字符串格式,如郵政編碼?
E.g. LLNNLL
使用我收到我已經把這個在一起,這似乎工作,但我想知道是否有做這個更容易或更有效的方式幫助。
import re
#enters and saves the input
postcode=input("Enter the postcode")
#uses the re command to set the format to check
pccheck=re.compile(r'[a-zA-Z]{2}\d{2}[a-zA-Z]{2}')
#checks if postcode matches the pattern
matching=pccheck.match(postcode)
#does this if the postcode does not match the format
if str(matching) =="None":
print("The postcode is irregular")
file=open("wrongcodes.txt","a")
file.write(str(postcode)+"\n")
file.close()
#does this if it does match
else:
print("The postcode is ok")
're'模塊將非常適合這一點,但是如果您向我們展示您所寫的一些試圖解決您遇到的問題的代碼,您將在StackOverflow中獲得更好的響應。這不是一個代碼寫入服務。 – 2014-09-25 16:24:05