Python中不区分大小写的字符串endswith()

要以不区分大小写的方式使用 str.endswith() 方法:

  1. 使用 str.lower() 将两个字符串都转换为小写。
  2. 对小写字符串使用 str.endswith() 方法。
string = 'zadmei.com'

substring = 'COM'

if string.lower().endswith(substring.lower()):
    # ?️ this runs
    print('The string ends with the substring (case-insensitive)')
else:
    print('The string does NOT end with the substring (case-insensitive)')


# ?️ True
print(
    string.lower().endswith(substring.lower())
)

Python中不区分大小写的字符串endswith()

str.lower() 方法返回字符串的副本,其中所有大小写字符都转换为小写。

在使用 str.endswith() 方法之前,我们使用 str.lower() 方法将两个字符串都转换为小写。

当两个字符串都转换为相同大小写时,我们可以以不区分大小写的方式使用 str.endswith() 方法。

如果我们的字符串包含非 ASCII 字母,请使用 str.casefold() 方法而不是 str.lower()

string = 'zadmei.com'

substring = 'COM'

if string.casefold().endswith(substring.casefold()):
    # ?️ this runs
    print('The string ends with the substring (case-insensitive)')
else:
    print('The string does NOT end with the substring (case-insensitive)')


# ?️ True
print(
    string.casefold().endswith(substring.casefold())
)

str.casefold() 方法返回字符串的大小写副本。

# ?️ using str.casefold()
print('ZADMEI'.casefold())  # ?️ zadmei
print('ß'.casefold())  # ?️ ss

# ?️ using str.lower()
print('ZADMEI'.lower())  # ?️ zadmei
print('ß'.lower())  # ?️ ß

大小写折叠类似于小写,但更具侵略性,因为它旨在删除字符串中的所有大小写区别。

请注意德语小写字母 ß 如何等于 ss。

由于字母已经是小写字母,str.lower() 方法按原样返回字母,而 str.casefold() 方法将其转换为 ss

如果我们只比较 ASCII 字符串,则不需要使用 str.casefold() 方法。 在这种情况下,使用 str.lower() 就足够了。