Python 通过忽略大小写比较两个字符串

Python 通过忽略大小写比较两个字符串

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

忽略大小写比较字符串

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

示例1

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

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的许多操作中广泛使用。在本文中,我们了解了如何通过忽略字符串的大小写来比较字符串。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程