禁用 Python 的 re.findall() 的"group becomes tuple"行为



当我在Python 2.x中使用包含两个或更多组的正则表达式时,re.findall()返回正则表达式包含的n个组的n元组列表。我知道它应该像这样工作,但是有什么方法可以规避这种行为吗?

例如,当我跑步时

import re
sentence = 'We also learned that the !!probability of an outcome is its relative frequency over endless repetitions of the experiment. '
print re.findall(r'[Pp]robabilit(y|ies)',sentence)

它只返回['y'] .但是,我希望probability返回。对于包含"概率"的不同句子,我希望返回probabilities,依此类推。

当存在一个或多个组时,re.findall的行为会发生变化。它返回组列表;元组列表(如果有多个组)。

您可以通过将组设置为非捕获组来获得所需的内容:

>>> re.findall(r'[Pp]robabilit(?:y|ies)',sentence)
['probability']

或者使用re.finditer和列表理解:

>>> [m.group() for m in re.finditer(r'[Pp]robabilit(y|ies)',sentence)]
['probability']

最新更新