首页 > 解决方案 > 从 Python 3.7 中的字符串中提取特定信息

问题描述

Python3.7

以下是我的输入:

一条“随机道路” (1,2) (2,3) (3,4)

a 是我添加道路的命令。接下来是道路名称及其位置。我需要提取道路的名称。

我希望提取道路名称及其坐标并存储在单独的列表中。我可以使用 re 提取整数,但无法提取道路名称。如何仅提取道路名称并将其存储在单独的字符串中。

标签: python-3.xstringlistchar

解决方案


也许使用拆分方法?

test_str = "Random Road (1,2) (2,3)(3,4)" 
print(test_str.split("(")[0].strip())

'Random Road'

编辑:如果道路名称在引号之间,则添加更简单的方法

import re
test_str = """a "Random Road" (1,2) (2,3)(3,4)"""
print(re.findall('"([^"]*)"', test_str))
['Random Road']

推荐阅读