Zubair Farooq
Zubair Farooq

Reputation: 123

How can i split string?

I'm trying to split string into address, city, state and zip code but unable to split successfully.

Here is my code:

address =  "4502 150th Pl SE, Bellevue, WA 98006"
my_add = address.split(',')
street = my_add[0] 
city = my_add[1]
state_zip = my_add[2]
state_zip = state_zip
state = state_zip.split(' ')
print(street)
print(city)
print(state_zip)
print(state)
# 4502 150th Pl SE
#  Bellevue
#  WA 98006
# ['', 'WA', '98006']

I expect that address will be split as:

can anyone help me to find best possible solution. Thanks

Upvotes: 1

Views: 80

Answers (5)

Engineero
Engineero

Reputation: 12948

You are getting some extra spaces in there, and since you are splitting on spaces, you end up with my_add[2] containing three elements: an empty string (comes before the first space), your state, and your zip code. You can add .strip() to your code to fix this:

street = my_add[0].strip()
city = my_add[1].strip()
state_zip = my_add[2].strip()  # remove extra spaces
state_zip = state_zip.split(' ')  # now split on space to get state and zip
state = state_zip[0]  # first element: state
zip_code = state_zip[1]  # second element: zip
print(street)
print(city)
print(state_zip)
print(state)
print(zip_code)
# 4502 150th Pl SE
# Bellevue
# ['WA', '98006']
# WA
# 98006

Upvotes: 2

Slayer
Slayer

Reputation: 882

One way to solve this

import re
re.split(', ', address)
*add1, city, state, zipcode = [x for x in re.split('[ ,]', address) if x!='']
add1 = ' '.join(add1)

Upvotes: 0

Anupam
Anupam

Reputation: 717

You can try this.

>>> address = "4502 150th Pl SE, Bellevue, WA 98006"
>>> my_add = address.split(',')
>>> street = my_add[0]
>>> street
'4502 150th Pl SE'
>>> city = my_add[1].strip()
>>> city
'Bellevue'
>>> state_zip = my_add[2].split()[1]
>>> state_zip
'98006'
>>> state = my_add[2].split()[0]
>>> state
'WA'

Hope it helps.

Upvotes: 0

Dylan Riley
Dylan Riley

Reputation: 429

I think your solution would be the code below:

address = "4502 150th Pl SE, Bellevue, WA 98006"
my_add = address.split(',')
street = my_add[0]
city = my_add[1]
state_zip = my_add[2]
state_zip_split = state_zip.split(' ')
state_zip = state_zip_split[2]
state = state_zip_split[1]
print("Street: ", street)
print("City: ", city)
print("State Zip: ", state_zip)
print("State: ", state)

You defined state_zip as an array, you needed to split it one more time to get the state and zip code

Upvotes: 1

sowlosc
sowlosc

Reputation: 480

If you are sure that a comma is always followed by a space, you can do this:

address =  "4502 150th Pl SE, Bellevue, WA 98006"

street, city, state_info = address.split(", ")
state, zipcode = state_info.split(" ")

print("address:", street)
print("city:", city)
print("state:", state)
print("zipcode:", zipcode)

Upvotes: 6

Related Questions