有条件地重新格式化字符串时出错

2024-06-13 09:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我昨天申请表的这一部分已经开始工作了,但我似乎不知道为什么它现在不起作用

它应该这样做:

输入:10th ave 501

输出:501 10th ave

这段代码应该在名为patterns的列表中搜索一个目标词,如果有一个数字后面有len <= 4,请将它移到字符串的前面patterns包含ave, street, road, place之类的单词

这是我的密码:

address = address.split(' ')
for pattern in patterns:
    try:
        if address[0].isdigit():
            continue
        location = address.index(pattern) + 1
        number_location = address[location]
        if 'th' in address[location + 1] or 'floor' in address[location + 1] or '#' in address[location]:
            continue
    except (ValueError, IndexError):
        continue
    if number_location.isdigit() and len(number_location) <= 4:
        address = [number_location] + address[:location] + address[location+1:]
        break
address = ' '.join(address)

print address

现在输出和我输入的完全一样。i、 e10th ave 501正在返回10th ave 501。我觉得这是比较明显的东西,我看了一下


Tags: or代码innumber列表lenifaddress
1条回答
网友
1楼 · 发布于 2024-06-13 09:19:06

'10th'.isdigit()False,因为:

Return true if all characters in the string are digits (source)

如果愿意,您只能检查第一个字符:

if number_location[0].isdigit() and len(number_location) <= 4:

相关问题 更多 >