import re
address1 = []
address2 = []
city = []
state = []
zipCode = []
modifiedShipping_address1 = (
['#### Example Rd. SE', 'City, OH\xa0#####', 'United States', ''],
['### Street Ct', 'Apt B', 'City, SC\xa0#####', 'United States', ''])
for i in modifiedShipping_address1:
address1.append(i[0])
if len(i) == 4:
address2.append('')
cityIndex = str(i[1]).find(',')
city.append(i[1][:cityIndex])
state_re = re.compile(', (.*?)\\xa0')
state_pat = re.findall(state_re, str(i[1]).strip())
for i in state_pat:
state.append(i)
zip_re = re.compile('\\xa0(.*?)')
zip_pat = re.findall(zip_re, str(i[1]).strip())
for i in zip_pat:
zipCode.append(i)
else:
address2.append(i[1])
cityIndex = str(i[2]).find(',')
city.append(i[2][:cityIndex])
state_re = re.compile(', (.*?)\\xa0')
state_pat = re.findall(state_re, str(i[2]).strip())
for i in state_pat:
state.append(i)
zip_re = re.compile('\\xa0(.*?)')
# This line throws the exception:
zip_pat = re.findall(zip_re, str(i[2]).strip())
for i in zip_pat:
zipCode.append(i)
state = state[:]
zipCode = zipCode[:]
print state
print zipCode
運行時,該代碼產生這樣的輸出:蟒蛇2.7迭代指數誤差
['OH']
[]
Traceback (most recent call last):
File "iterating.py", line 37, in <module>
zip_pat = re.findall(zip_re, str(i[2]).strip())
IndexError: string index out of range
如何去fixin呢?謝謝。我不明白indexError來自哪裏。
它不是有效的Python代碼,請修復縮進 – mykhal 2012-02-27 22:00:24
因此已修復 – phales15 2012-02-27 22:05:52
請提供一個完整的示例來演示您的問題。給定的代碼有很多問題可以阻止你的問題的再現:縮進仍然是非法的Python;有字符串缺少開始或結束引號; 「\ xa#」序列是無效字符串;地址1,地址2,城市,州和zipCode未申報。另外,還不清楚程序輸出的文本是什麼,它確實是完整的未修改的輸出。 – Weeble 2012-02-27 22:14:26