python - 如何从 python 中的字符串中提取多子字符串?

标签 python python-3.x string list

我需要帮助从一个字符串中提取多个子字符串并将其分配给一个列表,并且那些所需的子字符串具有相似的开始子字符串和结束子字符串,

例如,如果我有这样一个字符串:“开始某事某事结束开始什么都没有结束”

如何提取“something something”和“nothing nothing”并将其附加到列表中。

最佳答案

您可以使用 re.findall .


>>> text = 'start something something end start nothing nothing end'
>>> re.findall('start (.+?) end', text)
['something something', 'nothing nothing']

Return all non-overlapping matches of pattern in string, as a list of strings.

图案是

  • 开始后跟一个空格
  • (表示我们感兴趣的部分(组)的开始
  • .表示任意字符
  • +?表示至少有一个,但越少越好
  • )表示我们感兴趣的部分(组)结束
  • 一个空格后跟 end

The string is scanned left-to-right, and matches are returned in the order found.

If one or more groups are present in the pattern, return a list of groups;

我们正在使用组,如上所示

this will be a list of tuples if the pattern has more than one group.

我们只使用一组。

Empty matches are included in the result.

关于python - 如何从 python 中的字符串中提取多子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58672956/

相关文章:

python - 字符串在文件中的位置

string - 如何遍历平衡二进制字符串?

ios - 如何将 Swift String 桥接到 Objective C NSString?

javascript - 转义小于/大于 javascript

python - functools.partial : TypeError: got multiple values for keyword argument

python - 在学校项目中使用 Python 编写战舰游戏

python - 如何使用嵌套循环在 Python 中创建模式?

python - 根据 ID 值删除/保留 numpy 数组行

python - 将部分案例匹配到 Python 字典

python - 在字符串中查找列表元素