在Python中,字符串是字符序列,它们作为对象有效地存储在内存中。 每个对象都可以使用 id()
方法,如下所示。 Python 尝试重复使用内存中具有相同值的对象,这也使得在 Python 中比较对象非常快:
$ python
Python 3.9.0 (v3.9.0:9cf6752276, Oct 5 2020, 11:29:23)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "abc"
>>> b = "abc"
>>> c = "def"
>>> print (id(a), id(b), id(c))
(139949123041320, 139949123041320, 139949122390576)
>>> quit()
为了比较字符串,Python 提供了一些不同的运算符来执行此操作。 首先,我们将在下面更详细地解释它们。 其次,我们将回顾一下 string
和 re
模块,其中包含处理不区分大小写和不精确匹配的方法。 三、处理多行字符串 difflib 模块 相当方便。 许多示例将帮助您了解如何使用它们。
将 Strng 与 == 和 != 运算符进行比较
作为基本的比较运算符,您需要使用 ==
和 !=
。 它们的工作方式与整数和浮点值完全相同。 这 ==
操作员退货 True
如果存在完全匹配,否则 False
将被退回。 相比之下, !=
操作员退货 True
如果没有匹配则返回 False
. 清单1 证明了这一点。
在一个 for
循环中,将包含瑞士城市“洛桑”名称的字符串与其他位置列表中的条目进行比较,并将比较结果打印在标准输出上。
清单 1:
listOfPlaces = ["Berlin", "Paris", "Lausanne"]
currentCity = "Lausanne"
for place in listOfPlaces:
print (f"comparing {place} with {currentCity}: %{place == currentCity}")
运行上面的 Python 脚本,输出如下:
$ python3 comparing-strings.py
comparing Berlin with Lausanne: False
comparing Paris with Lausanne: False
comparing Lausanne with Lausanne: True
==
和 is
运营商
Python 有两个比较运算符 ==
和 is
。 乍一看它们似乎是一样的,但实际上却不然。
==
根据两个变量所代表的值来比较它们。 相比之下,is
运算符根据内存中的对象 ID 比较两个变量。
约翰(Doe)和约翰(Moe)都被称为约翰。 如果我们能把他们简化为只有他们的名字,他们在价值上是平等的,但在性质上仍然是两个不同的人。
下一个示例演示了三个具有字符串值的变量。 两个变量 a
和 b
具有相同的值,并且Python引用相同的对象以最小化内存使用。
默认情况下,这是针对简单类型和字符串执行的,但不适用于其他对象:
>>> a = 'hello'
>>> b = 'hello'
>>> c = 'world'
>>> a is b
True
>>> a is c
False
>>> id(a)
140666888153840
>>> id(b)
140666888153840
>>>
一旦值发生变化,Python 将重新实例化该对象并分配该变量。 在下一个代码片段中 b
得到值2,随后 b
和 c
引用同一个对象:
>>> b = 'world'
>>> id(b)
140666888154416
>>> id(c)
140666888154416
更多比较运算符
对于有关字典顺序的比较,您可以使用比较运算符 <
, >
, <=
及 >=
。 比较本身是逐字符进行的。 顺序取决于字母表中字符的顺序。 此顺序取决于执行 Python 代码时计算机上使用的字符表。
请记住,顺序区分大小写。 以拉丁字母为例,“Bus”出现在“bus”之前。 清单2 展示了这些比较运算符在实践中的工作原理。
清单 2:
listOfPlaces = ["Berlin", "Paris", "Lausanne"]
currentCity = "Lausanne"
for place in listOfPlaces:
if place < currentCity:
print (f"{place} comes before {currentCity}")
elif place > currentCity:
print (f"{place} comes after {currentCity}")
else:
print (f"{place} is equal to {currentCity}")
运行上面的 Python 脚本,输出如下:
$ python3 comparing-strings-order.py
Berlin comes before Lausanne
Paris comes after Lausanne
Lausanne is equal to Lausanne
不区分大小写的字符串比较
前面的示例重点关注字符串之间的精确匹配。 为了允许不区分大小写的比较,Python 提供了特殊的字符串方法,例如 upper()
和 lower()
。 它们都可以直接用作相应字符串对象的方法。
upper()
将整个字符串转换为大写字母,并且 lower()
分别转换为小写字母。 基于 清单1 下一个清单显示了如何使用 lower()
方法。
查看我们的 Git 学习实践指南,其中包含最佳实践、行业认可的标准以及随附的备忘单。 停止谷歌搜索 Git 命令,实际上 学习 它!
清单 3:
listOfPlaces = ["Berlin", "Paris", "Lausanne"]
currentCity = "lausANne"
for place in listOfPlaces:
print (f"comparing {place} with {place.lower() == currentCity.lower()}: {currentCity}")
输出如下:
$ python3 comparing-strings-case-insensitive.py
comparing Berlin with lausANne: False
comparing Paris with lausANne: False
comparing Lausanne with lausANne: True
使用正则表达式 (RegEx) 比较字符串
A 正则表达式 – 或简称“正则表达式” – 定义特定的字符模式。
要在 Python 中使用此机制,请导入 re
模块 首先定义一个特定的模式,然后。 同样,以下示例基于 清单1。 搜索模式与“bay”匹配,并以小写或大写字母开头。 准确地说,以下 Python 代码会查找出现搜索模式的所有字符串,无论字符串位于开头、中间还是末尾。
清单 4:
import re
listOfPlaces = ["Bayswater", "Table Bay", "Bejing", "Bombay"]
pattern = re.compile("[Bb]ay")
for place in listOfPlaces:
if pattern.search(place):
print (f"{place} matches the search pattern")
输出如下,并匹配地点列表中的“Bayswater”、“Table Bay”和“Bombay”:
$ python3 comparing-strings-re.py
Bayswater matches the search pattern
Table Bay matches the search pattern
Bombay matches the search pattern
多行和列表比较
到目前为止,我们的比较只是几个词。 使用 difflib
Python 模块还提供了一种比较多行字符串和整个单词列表的方法。 可以根据 diff 工具的各种格式配置输出。
下一个例子(清单5) 逐行比较两个多行字符串,并显示删除和添加。 初始化之后 Differ
第 12 行中的对象使用以下内容进行比较 compare()
第 15 行中的方法。结果打印在标准输出上:
import difflib
original = ["About the IIS", "", "IIS 8.5 has several improvements related", "to performance in large-scale scenarios, such", "as those used by commercial hosting providers and Microsoft's", "own cloud offerings."]
edited = ["About the IIS", "", "It has several improvements related", "to performance in large-scale scenarios."]
d = difflib.Differ()
diff = d.compare(original, edited)
print ('n'.join(diff))
运行该脚本会创建如下所示的输出。 删除的行由 -
符号,而带有添加的行以 a 开头 +
符号。 此外,有变化的行以问号开头。 使用指示更改 ^
相应位置有标志。 没有指示器的行仍然相同:
$ python comparing-strings-difflib.py
About the IIS
- IIS 8.5 has several improvements related
? ^^^^^^
+ It has several improvements related
? ^
- to performance in large-scale scenarios, such
? ^^^^^^
+ to performance in large-scale scenarios.
? ^
- as those used by commercial hosting providers and Microsoft's
- own cloud offerings.
结论
在本文中,您学习了在 Python 中比较字符串的各种方法。 我们希望本概述可以帮助您在开发人员的生活中有效地进行编程。
致谢
作者要感谢 Mandy Neumeyer 在准备本文时提供的支持。