首页 > 解决方案 > 在Python中比较2个字符串的最有效方法是什么

问题描述

我正在寻找比较两个字符串的最有效方法,但我不确定哪个更好:==in. 还是有其他方法比这两种方法更有效?

编辑:我正在尝试检查是否相等

标签: pythonpython-3.xperformance

解决方案


他们做不同的事情。

==相等性测试:

"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).


推荐阅读