Search code examples
pythonarraysstringsplitstrsplit

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

into:

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

Thank you.


Solution

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