如何分割字符串?

时间:2019-04-02 19:56:16

标签: python

我正在尝试将字符串拆分为地址,城市,州和邮政编码,但无法成功拆分。

这是我的代码:

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']

我希望该地址将被拆分为:

  • 地址:4502 150th Pl SE
  • city:贝尔维尤
  • 州:WA
  • 邮政编码:98006

谁能帮助我找到最好的解决方案。谢谢

5 个答案:

答案 0 :(得分:5)

如果确定逗号后面总是有空格,则可以执行以下操作:

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)

答案 1 :(得分:2)

您将在其中获得一些额外的空格,并且由于要在空格上进行拆分,因此您最终得到的 Sample Timepoint CountA CountB PercentA PercentB CountC Normalization 0 1 1 1.0 2.0 40 30 5.0 0.1 1 2 1 4.0 2.0 25 35 20.0 0.2 2 2 2 25.0 10.0 20 22 20.0 0.5 包含三个元素:空字符串(在第一个空格之前),状态和zip码。您可以在代码中添加my_add[2]来解决此问题:

.strip()

答案 2 :(得分:1)

我认为您的解决方案将是以下代码:

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)

您将state_zip定义为一个数组,您需要再将其拆分一次才能获得状态和邮政编码

答案 3 :(得分:0)

您可以尝试一下。

>>> 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'

希望有帮助。

答案 4 :(得分:0)

一种解决方法

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