python - re.findall() 和 str.count('str') 有什么区别?
问题描述
re.findall() 和 str.count('str') 有什么区别?除此之外
str.count('str')
返回出现次数
和
re.findall(pattern, 'str')
返回每个外观的列表。
各有什么好处?我应该什么时候选择每个?哪种方法更可取?
解决方案
他们不一样。考虑以下示例:
>>> a = "123strxyz"
>>> a.count("str.")
0
>>> re.findall("str.", a)
['strx']
findall
接受一个正则表达式,所以在第二个例子中,它在字符串中找到“strx”,而count
函数没有找到实际的点(因为它试图匹配文字点)。
推荐阅读
- typescript - 使用 TypeScript 声明从 mixin 中访问超类属性
- php - 带有 Pivot -> 子项的嵌套项目不会获取数据透视表数据
- c - 将带有逗号的整数扫描成二维数组时出现问题
- javascript - Javascript | 在 For 循环之后执行
- javascript - 如何使用 jquery 为我附加一个 div,其中还包括它的所有嵌套 div?
- javascript - 为什么单击按钮时表单发布会自动执行?
- python-3.x - sum 函数如何与 NaN 元素一起使用?
- c++ - 从输入文件中读取复合键和数值的正确方法是什么?
- angular - 如何将视频文件作为 Angular 块上传(版本 8)
- postgresql - Postgres 可以在单个查询中使用多个索引吗?