Python casefold

Python 的 casefold 函数将给定字符串中的所有字符转换为小写字母。虽然这与 lower 函数相同,但它更积极、更强大。

此方法在比较字符串时非常有用。此字符串 casefold 函数的语法是:

String_Value.casefold()

Python casefold 示例

以下示例集可帮助您理解此方法。

Str1 = 'leaRn PYTHON PrOGRAms AT tutOrial gateWay'
 
Str2 = Str1.casefold()
print('First Output after is = ', Str2)
 
# Observe the Difference between Original and other
print('Original is = ', Str1)
print('Second Output is = ', Str1.casefold())
 
# Use directly
Str3 = 'LearN pYTHON proGramminG'.casefold()
print('Third Output after is = ', Str3)
 
Str4 = 'pyTHon ProGRAmming 1234 tuTorIal'.casefold()
print('Fourth Output after is = ', Str4)
First Output after is =  learn python programs at tutorial gateway
Original is =  leaRn PYTHON PrOGRAms AT tutOrial gateWay
Second Output is =  learn python programs at tutorial gateway
Third Output after is =  learn python programming
Fourth Output after is =  python programming 1234 tutorial

此 casefold 函数在字符串比较中非常有用。下面的 Python 示例比较了具有相同单词不同大小写字符的字符串。首先,我们在不使用此方法的情况下进行比较。接下来,我们在 If 语句中使用此 函数。请参阅 lower 方法文章。

Str1 = 'PYthoN'
Str2 = 'pyTHon'
 
if(Str1 == Str2):
    print('Both are equal')
else:
    print('Not Equal')
           
if(Str1.casefold() == Str2.casefold()):
    print('Both are equal')
else:
    print('Not Equal')
Not Equal
Both are equal

此 casefold 示例与上述示例相同。但是,这次我们允许用户输入自己的句子。接下来,我们比较这些文本。

str1 = input("Please enter the First String : ")
str2 = input("Please enter the Second String : ")
 
if(str1.casefold() == str2.casefold()):
    print('Both are equal')
else:
    print('Not Equal')
String casefold Example