Python:如何从字符串中提取所需信息?

Bru*_*uce 1 python

我是Python的新手.Python中是否有StringTokenizer?我可以通过字符扫描和复制来进行角色扮演.

我有以下输入字符串

data = '123:Palo Alto, CA -> 456:Seattle, WA 789'
Run Code Online (Sandbox Code Playgroud)

我需要从这个字符串中提取两个(城市,州)字段.这是我写的代码

name_list = []
while i < len(data)):
      if line[i] == ':':
          name = ''
          j = 0
          i = i + 1
          while line[i] != '-' and line[i].isnumeric() == False:
             name[j] = line[i]   # This line gives error
             i = i + 1
             j = j + 1
          name_list.append(name)
      i = i + 1
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

Nic*_*k T 8

data = '123:Palo Alto, CA -> 456:Seattle, WA 789'
citys = []
for record in data.split("->"):
    citys.append(
        re.search(r":(?P<city>[\w\s]+),\s*(?P<state>[\w]+)",record)
        .groupdict()
    )

print citys
Run Code Online (Sandbox Code Playgroud)

得到:

[{'city': 'Palo Alto', 'state': 'CA'}, {'city': 'Seattle', 'state': 'WA'}]