Home Ask Login Register

Developers Planet

Your answer is one click away!

Vkitor February 2016

Python Splitting string by number and space

Hy, could please someone help me? I have a lot of strings that contain addresses and i need to split them to get street name, house number and country in array.

something like this:

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


['streetA','15','New York']
['street number 2','35','California']

Thank you.


Brendan Abel February 2016

You could use regular expressions.

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')

Here is an example on regex101.

Rawly February 2016

Just use .split(',') to get country (last item) then find last space in the first item:

>>> 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']

Alessiox February 2016

@Brendan Abel solution is good, although it returns a tuple and not a list.

You can convert it to a list using the list() function and this will match your output:

import re

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

m = regex.match('streetA 15, New York')
print result
# ['streetA', '15', 'New York']

zondo February 2016

You don't need to use 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]

For your examples, it prints:

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

Post Status

Asked in February 2016
Viewed 3,551 times
Voted 7
Answered 4 times


Leave an answer

Quote of the day: live life