设置向上
我有包含英国格式地址的字符串,例如address = '6A McCarthy Way'
。
我需要从地址获取门牌号码,例如house_number = '6A
当前代码
我有以下工作代码,
position = re.search('\d+', address).start()
if position == 0:
for i in range(0,100000):
if address[position + i] != ' ':
house_number = address[:position + i + 1]
else:
break
else:
house_number = address[position:]
对于address = '6A McCarthy Way'
和address = 'McCarthy Way 6A'
,代码都会返回house_number = '6A'
。
问题
此代码假设
address
address = '6A, McCarthy Way'
或address = '6 McCarthy Way'
address
没有错误 - 例如永远不会address = '6AMcCarthy Way'
最后,即使假设适用于所有情况,我也不确定这是做这种情况的最蟒蛇方式。
如何改进代码?
答案 0 :(得分:3)
使用re.search
import re
address = '6A McCarthy Way'
address2 = 'McCarthy Way 6A'
address3 = 'McCarthy Way 6AAAA'
print(re.search("(\d+\w*)", address).group())
print(re.search("(\d+\w*)", address2).group())
print(re.search("(\d+\w*)", address3).group())
<强>输出:强>
6A
6A
6AAAA