比较 Python 中的字符串
2023-09-22 03:33:39
在 Python 中,string是一个不可变的对象。variable只是给内存中对象的标签。这意味着,如果两个变量被分配了相同的字符串值,它们实际上引用了内存中的同一字符串对象。这一事实可以通过检查其id()值来验证。
str1="Hello"
str2="Hello"
str3="HELLO"
print (id(str1), id(str2), id(str3))
输出:
1215823728944 1215823728944 1215823729648
因此,用于检查相等性的比较运算符==
返回True
两个字符串操作数是否具有相同的id()值,否则False
返回。
print(str1 == str2)
print(str1 == str3)
输出:
True
False
Python 也有!=
运算符(读作不等于),如果字符串操作数的值不同id()
则显然返回True
,如果相同,则返回False
。
print(str1 != str2)
print(str1 != str3)
输出:
False
True
Python 还有一个名为 is
的标识运算符。此运算符计算True
两个操作数中是否id
相同。
print(str1 is str2)
print(str1 is str3)
输出:
True
False
还有is not
运算符,正好相反。
print (str1 is not str2)
print (str1 is not str3)
输出:
False
True
从表面上看,==
和IS运营商的行为似乎相似。但是,请考虑以下示例。
var1="Tutorials"
var2="Teacher"
var3="python114.com"
print(var1+var2 == var3)
print(var1+var2 is var3)
输出:
True
False
即使var1 + var2
的串联计算结果为 var3
,与使用 var3 进行比较 ==
返回True
但使用 is 返回False
。
比较运算符==, !=, <, > <= and >=
根据字母的字典顺序执行字符串比较。
每个字符串中字母的 Unicode 值将逐个比较。>
和<
运算符的结果取决于索引处字母的 Unicode 值,因为它们不相同。
例如,"bat" > "ball"
返回 True
,这仅表示第一个字符串按字母顺序出现在第二个字符串之后。
print("bat">"ball")
print("car">"cat")
输出:
True
False
这是因为字符串的比较位置中断,Unicode 值t
大于l
和r
。
print(ord('t'), ord('l')) #in first comparison
print(ord('r'), ord('t')) #in second comparison
输出:
116 108
114 116
显然,字符串比较区分大小写,因为小写字母的 Unicode 值大于大写字母的值。 如果要在不考虑大小写的情况下比较字符串,请将它们转换为大写或小写。
str1="Hello"
str3="HELLO"
print (str1.upper()>=str3)
输出:
True
最后,我们简要介绍一下re
模块中定义的match()
和search()
函数。
Python 的 re 模块实现了正则表达式语法,用于查找字符串中字母模式的外观。match()
函数检查是否在字符串的开头找到给定的模式。
另一方面,search()
函数能够检查其在字符串中任何位置的存在。另一个函数,findall()
返回模式的所有外观。
import re
string="Simple is better than complex"
pattern="Simple"
if re.match(pattern, string):
print ("found match")
else:
print("match not found")
pattern="dummy"
if re.match(pattern, string):
print ("found match")
else:
print("match not found")
pattern="ple"
obj=re.search(pattern, string)
print ("found pattern at ", obj.start())
obj=re.findall(pattern, string)
print (obj)
输出:
found match
match not found
found pattern at 3
['ple', 'ple']
要查找图案的每个外观的位置,请使用finditer()
函数。
obj=re.finditer(pattern, string)
for app in obj:
print ("found pattern at index : ", app.start())
输出:
found pattern at index : 3
found pattern at index : 25
re模块功能强大得多,能够搜索复杂的字符串模式,例如字母数字字符串,搜索时忽略大小写,转义字符等。 此高级讨论超出了本文的范围。