python - 在Python中比较2个字符串的最有效方法是什么
问题描述
我正在寻找比较两个字符串的最有效方法,但我不确定哪个更好:==
或in
. 还是有其他方法比这两种方法更有效?
编辑:我正在尝试检查是否相等
解决方案
他们做不同的事情。
==
相等性测试:
"tomato" == "tomato" # true
"potato" == "tomato" # false
"mat" == "tomato" # false
in
测试substring,并且可以被认为是(可能)更有效的版本str.find() != -1
):
"tomato" in "tomato" # true
"potato" in "tomato" # false
"mat" in "tomato" # true <-- this is different than above
在这两种情况下,它们都是最有效的方式来做他们所做的事情。如果您使用它们来比较两个字符串实际上是否相等,那么当然strA == strB
比(strA in strB) and (strB in strA)
.
推荐阅读
- microservices - 微服务的数据库架构
- linux - Linux 命令行:id、group 和 getent group 不返回相同的结果
- ruby-on-rails - 具有多个实例的 Rails 迁移
- java - 在 groovy 上包含转义斜杠的文字字符串
- arrays - 获取数组 lop 中的所有 json 值
- firebase - Cloud Functions for Firebase - 检索已部署的代码?
- python - 在 Windows 上使用 sys.path.append for C:\... in IDLE
- html - 无法在css中居中导航栏
- python - 从 python 列表中获取特定元素的索引
- firebase - Firestore:如何按数组对象的字段使用顺序