【发布时间】:2018-05-02 08:15:52
【问题描述】:
设置
我有包含英国格式地址的字符串,例如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的开头或结尾 - 门牌号和地址将仅采用上述 2 种格式 - 例如从不
address = '6A, McCarthy Way'或address = '6 McCarthy Way' -
address中没有错误——例如从不address = '6AMcCarthy Way'
最后,即使假设适用于所有情况,我也不确定这是最 Pythonic 的方式。
如何改进代码?
【问题讨论】:
-
一般来说,正则表达式不会捕捉到“错误”,因为它们的本质是期待某种模式。