How do you substring in Python?

Posted on 2007-10-01
Last Modified: 2008-01-09
I have a address "Santa Mora, AZ 86444
I want to substring this string into city, state and zip but what is the best way to do this?
Do I use partition, rfind, or or split?
Question by:jamie_lynn
    LVL 9

    Assisted Solution

    i assume this is only just one string, and that "Santa mora" is city, AZ is state, and the number after AZ is then

    >>> s="Santa Mora, AZ 86444"
    >>> splitted=s.split(",")
    >>> splitted
    ['Santa Mora', ' AZ 86444']
    >>> city=splitted[0]
    >>> splitted2=splitted[1].split()
    >>> splitted2
    ['AZ', '86444']
    >>> state,zip=splitted2[0],splitted2[1]
    >>> state,zip
    ('AZ', '86444')
    LVL 28

    Expert Comment

    You can also take advantage of the multiple assignment command. If you are sure about the form of the addres, you can get rid of the temporary list name and of its indexing. The result may be more readable:

    >>> s = 'Santa Mora, AZ 86444'
    >>> city, XXzip = s.split(',')
    >>> state, zip = XXzip.split()
    >>> city
    'Santa Mora'
    >>> state
    >>> zip

    If there are more complicated cases, regular expressions can be also good for extraction of the parts of the address string. However, do it without regular expression if it is easy to do it in the alternative way.
    LVL 15

    Assisted Solution

    import re
    city, state, zip = [i for i in re.split(r'[, ]', s) if i]
    LVL 28

    Assisted Solution

    mish33: You did not try it, do you? ;)

    >>> city, state, zip = [i for i in re.split(r'[, ]', s) if i]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: too many values to unpack

    The problem is that not every space is a separator. The split will do the following:

    >>> lst = [i for i in re.split(r'[, ]', s) if i]
    >>> lst
    ['Santa', 'Mora', 'AZ', '86444']

    The usuall funny comment about using regular expressions holds ;)

    LVL 28

    Accepted Solution

    If you really want to use a regular expression for extracting the info, try something like that:

    >>> import re
    >>> s = 'Santa Mora, AZ 86444'
    >>> rexAddress = re.compile(r'^\s*(?P<city>.+?)\s*,\s*(?P<state>[A-Z]+)\s*(?P<zip>\d+)\s*$')
    >>> m = rexAddress.match(s)
    >>> m
    <_sre.SRE_Match object at 0x00D452F0>
    >>> bool(m)
    'Santa Mora'

    However, it is not difficult to make an error in the regular expression...

    Author Comment

    Thanks everyone.   I did parse it, but I just wanted to know how everyone else did it to see if I parsed correctly.

    Featured Post

    Training Course: Java/J2EE and SOA

    This course will cover both core and advanced Java concepts like Database connectivity, Threads, Exception Handling, Collections, JSP, Servlets, XMLHandling, and more. You'll also learn various Java frameworks like Hibernate and Spring.

    Join & Write a Comment

    Suggested Solutions

    Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
    Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
    Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
    Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now