[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


How do you substring in Python?

Posted on 2007-10-01
Medium Priority
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

Assisted Solution

ghostdog74 earned 400 total points
ID: 19996648
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 29

Expert Comment

ID: 19996787
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

mish33 earned 400 total points
ID: 19996818
import re
city, state, zip = [i for i in re.split(r'[, ]', s) if i]
Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

LVL 29

Assisted Solution

pepr earned 1200 total points
ID: 19997224
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 29

Accepted Solution

pepr earned 1200 total points
ID: 19997257
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)
>>> m.group('city')
'Santa Mora'
>>> m.group('state')
>>> m.group('zip')

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

Author Comment

ID: 20004416
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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
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…
Suggested Courses

872 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