Python按数字和空格拆分字符串

时间:2016-02-08 17:55:51

标签: python arrays string split strsplit

Hy,可以请别人帮帮我吗?我有很多字符串包含地址,我需要拆分它们以获得街道名称,门牌号码和国家/地区。

类似的东西:

streetA 15, New York
street number 2 35, California
streetB 36B, Texas

成:

['streetA','15','New York']
['street number 2','35','California']
['streetB','36B','Texas']

谢谢。

4 个答案:

答案 0 :(得分:1)

只需使用.split(',')获取国家/地区(最后一项),然后找到第一项中的最后一个空格:

>>> l = 'street number 2 35, California'.split(',')
>>> index = l[0].rfind(' ')
>>> l = [l[0][:index]] + [l[0][index+1:]]+ [l[1].strip()]
>>> l
['street number 2', '35', 'California']

答案 1 :(得分:1)

您无需使用re.compile()

import re

def splitup(string):
    match = re.search(" \\d[^ ]*, ", string)
    if match is None:
        raise ValueError("Not a valid string: %r" % string)
    street = string[:match.start()]
    number = string[match.start(): match.end()].strip(", ")
    state = string[match.end():]
    return [street, number, state]

对于您的示例,它会打印:

['streetA', '15', 'New York']
['street number 2', '35', 'California']
['streetB', '36B', 'Texas']

答案 2 :(得分:0)

您可以使用正则表达式。

import re

regex = re.compile(r'^(.+) (\d+\w*), (.+)$')

m = regex.match('streetA 15, New York')
print m.groups()
# ('streetA', '15', 'New York')

m = regex.match('street number 2 35, California')
print m.groups()
# ('street number 2', '35', 'California')

这是example on regex101

答案 3 :(得分:0)

@Brendan Abel解决方案很好,虽然它返回一个元组而不是列表。

您可以使用list()功能将其转换为列表,这将与您的输出相匹配:

import re

regex = re.compile(r'^(.+) (\d+\w*), (.+)$')

m = regex.match('streetA 15, New York')
result=list(m.groups())
print result
# ['streetA', '15', 'New York']
相关问题