Tutorial Study Image

Python casefold()

Python 中的 casefold() 函数通过移除字符串中所有的大小写区别,将字符串转换为小写。这类似于 lower() 方法,但 casefold() 更强大和彻底。


string.casefold() 
 

casefold() 参数

casefold() 方法不接受任何参数。此方法在比较两个字符串时可以找到更多匹配项,并将更多字符转换为小写。

casefold() 返回值

返回值始终是一个字符串。此方法在字符串比较时忽略大小写。

输入 返回值
字符串 折叠大小写的字符串

Python 中 casefold() 方法的示例

示例 1:使用 casefold() 进行 Python 小写转换


string = "HOW ARE YOU"

# print lowercase string
print("After lowercase conversion:", string.casefold())
 

输出


After lowercase conversion: how are you

示例 2:使用 casefold() 进行严格转换


string1 = "der Fluß"
string2 = "der Fluss"

# ß is equivalent to ss
if string1.casefold() == string2.casefold():
    print('The given strings are equal.')
else:
    print('The given strings are not equal.')
 

输出


The given strings are equal.

注意:德语小写字母 ß 本身已经是小写,casefold() 会将其转换为 ss,而如果使用 lower() 方法则不会进行任何操作。