忽略大小写的Python字符串比较程序


在Python中,我们可以使用比较运算符,例如“==”、“!=”、“<”、“>”、“<=”、“>=”,以及Python内置函数,例如lower()和upper()方法来忽略大小写地比较两个字符串。字符串是用双引号括起来的字符序列。这些运算符根据分配给字符串每个字符的Unicode代码点来比较字符串。在本文中,我们将了解如何忽略字符串大小写进行比较。

忽略大小写的字符串比较

要在Python中忽略大小写地比较两个字符串,我们可以使用lower()或upper()函数,它们分别将字符串转换为小写或大写。一旦字符串完全转换为小写或大写,我们就可以忽略字符串的大小写进行比较。

示例1

在下面的示例中,我们使用lower()方法将字符串转换为小写。然后,我们使用“==”运算符比较两个字符串。由于两个字符串相同,代码的输出将是“忽略大小写,字符串相等”。

string1 = "Hello"
string2 = "hello"
if string1.lower() == string2.lower():
   print("The strings are equal, ignoring case.")
else:
   print("The strings are not equal, ignoring case.")

输出

The strings are equal, ignoring case.

示例2

我们还可以提示用户输入他自己的字符串进行比较。在下面的示例中,我们获取两个字符串,然后使用lower()函数将这两个字符串都转换为小写,然后使用“==”运算符比较这两个字符串。

string1 = "welcome To tutorials Point"
string2 = "Welcome to Tutorials point"
if string1.lower() == string2.lower():
   print("The strings are equal, ignoring case.")
else:
   print("The strings are not equal, ignoring case.")

输出

The strings are equal, ignoring case.

结论

在Python中比较字符串可以通过使用Python内置函数lower()和upper()来完成,它们分别在比较之前将字符串转换为小写和大写。这种不区分大小写的比较广泛用于Python中的许多操作。在本文中,我们了解了如何忽略字符串的大小写进行比较。

更新于:2023年4月17日

9K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.