Link to home
Create AccountLog in
Avatar of jamie_lynn
jamie_lynn

asked on

How do you substring in Python?

Hi,
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?
Thanks
Jamie
SOLUTION
Avatar of ghostdog74
ghostdog74

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of pepr
pepr

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
'AZ'
>>> zip
'86444'

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.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of jamie_lynn

ASKER

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