2014-09-25 40 views
-6

我是一個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") 
+2

're'模塊將非常適合這一點,但是如果您向我們展示您所寫的一些試圖解決您遇到的問題的代碼,您將在StackOverflow中獲得更好的響應。這不是一個代碼寫入服務。 – 2014-09-25 16:24:05

回答

2

如上所述,您需要re模塊。

import re 

post_code = re.compile(r'[a-zA-Z]{2}\d{2}[a-zA-Z]{2}') 

matching = post_code.match('AB12CD') # this is true 
another_matching = post_code.match('1AB3BC') # this is false 

[a-zA-Z]爲字母,\d爲數字([0-9])快捷方式,長正好兩個字符{2}裝置。

我希望這可以幫助你。有關更多信息,請查看正則表達式的手冊。

+1

我相信\ w是字母數字,所以它也會匹配0-9 – icedtrees 2014-09-25 16:52:08

+0

是的,你是對的,我會解決這個問題。我打字的速度很快,沒有多想。謝謝! – cezar 2014-09-25 16:57:13

相關問題