2011-06-27 43 views
2

如何在python中刪除郵政編碼中的+4?在郵編中刪除 - ####

我有數據,如

85001 
52804-3233 
Winston-Salem 

而且我想,要成爲

85001 
52804 
Winston-Salem 
+2

你試過到目前爲止有什麼解決辦法嗎? – Thomas

回答

2

你可以嘗試這樣的事:

for input in inputs: 
    if input[:5].isnumeric(): 
     input = input[:5] 
     # Takes the first 5 characters from the string 

只是帶走的東西都在前5位數字的前5個字符。

+0

我想你的意思是'input [0:4]'? – ram1

+3

不,在Python切片中,你指出你想要的第一個字符,然後是你*不需要的第一個字符。 '[0:5]'是列表或字符串的前五個元素。 – kindall

+0

我的錯誤。謝謝! – ram1

3
>>> zip = '52804-3233' 
>>> zip[:5] 
'52804' 

...當然,當你從你要把原始數據解析你的線條插入一些規則來區分郵編到修正和其他字符串,但我不知道你的數據是怎麼樣的,所以我不能幫忙(你可以檢查它們是否只有數字和' - '符號,也許?)。

2
>>> import re 
>>> s = "52804-3233" 
>>> # regex to remove a dash and 4 digits after the dash after 5 digits: 
>>> re.sub('(\d{5})-\d{4}', '\\1', s) 
'52804' 

\\1是所謂的反向引用,並得到由第一組,這將是在這種情況下,5位郵政編碼取代。

2
re.sub('-\d{4}$', '', zipcode) 
+0

這不是我。我upvoted你的答案。 – ram1

1

這抓起格式00000-0000用空格或其他單詞邊界的所有項目前後的編號,與前五位數字替換它。發佈的其他正則表達式將匹配您可能不需要的其他數字格式。

re.sub('\b(\d{5})-\d{4}\b', '\\1', zipcode) 
1

或者沒有正則表達式:

output = [line[:5] if line[:5].isnumeric() and line[6:].isnumeric() else line for line in text if line]