首页 > 解决方案 > re.findall() 和 str.count('str') 有什么区别?

问题描述

re.findall() 和 str.count('str') 有什么区别?除此之外

str.count('str')

返回出现次数

 re.findall(pattern, 'str')

返回每个外观的列表。

各有什么好处?我应该什么时候选择每个?哪种方法更可取?

标签: pythonpython-3.x

解决方案


他们不一样。考虑以下示例:

>>> a = "123strxyz"
>>> a.count("str.")
0
>>> re.findall("str.", a)
['strx']

findall接受一个正则表达式,所以在第二个例子中,它在字符串中找到“strx”,而count函数没有找到实际的点(因为它试图匹配文字点)。


推荐阅读