禁用";“组变为元组”;Python的行为&x27;s re.findall()
当我在Python 2.x中使用包含两个或多个组的正则表达式时,禁用";“组变为元组”;Python的行为&x27;s re.findall(),python,regex,string,python-2.7,Python,Regex,String,Python 2.7,当我在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. ' p
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']
。但是,我希望返回概率
。对于包含“概率”的另一个句子,我希望返回概率
,以此类推。存在一个或多个组时的更改行为。它返回一个组列表;如果有多个组,则为元组列表
通过将组设置为非捕获组,您可以获得所需的内容:
>>> re.findall(r'[Pp]robabilit(?:y|ies)',sentence)
['probability']
或者使用和列表理解:
>>> [m.group() for m in re.finditer(r'[Pp]robabilit(y|ies)',sentence)]
['probability']