Python String casefold()

时间:2020-02-23 14:43:23  来源:igfitidea点击:

Python字符串casefold()函数返回字符串的casefolded副本。
此函数用于执行不区分大小写的字符串比较。

Python String casefold()

我们来看一个casefold()函数的简单示例。

s = 'My name is hyman'

print(s.casefold())

s1 = 'Python'
s2 = 'PyThon'
print(s1.casefold() == s2.casefold())

输出:

my name is hyman
True

在上面的程序中,casefold()函数看起来与字符串lower()函数完全相同。
实际上,当字符串由ASCII字符组成时,效果是一样的。

但是,casecase折叠更具攻击性,它旨在删除字符串中的所有大小写区别。

例如,德语小写字母"ß"等效于" ss"。
由于已经是小写字母,lower()不会对"ß"产生任何作用,但casefold()会将其转换为" ss"。

让我们看另一个示例来确认这种行为。

s1 = 'ß'  # typed with Option+s in Mac OS
s2 = 'ss'
s3 = 'SS'
if s1.casefold() == s2.casefold():
  print('s1 and s2 are equals in case-insensitive comparison')
else:
  print('s1 and s2 are not-equal in case-insensitive comparison')

if s1.casefold() == s3.casefold():
  print('s1 and s3 are equals in case-insensitive comparison')

输出:

s1 and s2 are equals in case-insensitive comparison
s1 and s3 are equals in case-insensitive comparison