Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a string based on common delimeter in Python

I'd like to take the following string and slice it based on the pipe delimeter:

address = '1234 Broadway Ave | Los Angeles | CA | 94530'

I figured out the first piece:

street = address[:address.index('|')]
print(street)
1234 Broadway Ave

But I am unclear on how to get city/state/zip:

city = 
state = 
zip =

Also, is there a better way to do this? Using RegEx or something similar? Haven't used that before..

Thanks!

like image 526
JD2775 Avatar asked Jul 13 '26 09:07

JD2775


1 Answers

You can get each item by just splitting on '|' with str.split(), and using str.strip() to take away the leading and trailing whitespace of each item:

address = '1234 Broadway Ave | Los Angeles | CA | 94530'

items = [x.strip() for x in address.split('|')]

print(items)

Which gives:

['1234 Broadway Ave', 'Los Angeles', 'CA', '94530']

Additionally, you can also do this nicely with map():

items = list(map(str.strip, address.split('|')))

You could also assign these items to a dictionary using zip(), like so:

contents = ["street", "city", "state", "zip"]
d = dict(zip(contents, items))
print(d)

Which would give you this structure:

{'street': '1234 Broadway Ave', 'city': 'Los Angeles', 'state': 'CA', 'zip': '94530'}

Then you could access each item in this dictionary by simply calling the keys:

>>> d['street']
1234 Broadway Ave
>>> d['city']
Los Angeles
>>> d['state']
CA
>>> d['zip']
94530
like image 200
RoadRunner Avatar answered Jul 16 '26 06:07

RoadRunner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!