Python String比较
时间:2020-02-23 14:43:23 来源:igfitidea点击:
在本教程中,我们将看到如何在Python中比较两个字符串。
我们没有任何特定方法可以在Python中比较字符串。
我们可以使用不同的运算符如== =!用于字符串比较。
我们还可以使用<,>,<=,> =带字符串。
让我们通过示例来理解:
str1 = "hello" str2 = "hello" str3 = "HELLO" str4= "hi" print(str1==str2) print(str1==str3) print(str1 > str3) print(str1!=str4)
让我们现在了解输出。
str1 == str2返回true:由于str1和str2与字符串完全相同,它返回true。
str1 == str3返回false:在str1和str2不同时,它返回false。
str1> str3返回true:>运算符检查Unicode,在这种情况下返回true。
str1!= str4返回true,因为str1和str4不等于,它返回true。
不区分大小写的字符串比较
如果要按不区分大小写的情况进行比较字符串,则需要使用字符串使用Upper()或者更低()。
str1 = "hello" str2 = "HELLO" print(str1.lower()==str2.lower()) print(str1.upper()==str2.upper())
输出:
True True
在Python中,字符串作为字符序列存储,我们可以使用ID()函数来标识对象。
str1 = "hello" str2 = "hello" str3 = "HELLO" print(id(str1)) print(id(str2)) print(id(str3))