Python中不区分大小写的字符串endswith()
要以不区分大小写的方式使用 str.endswith() 方法:
- 使用 str.lower() 将两个字符串都转换为小写。
- 对小写字符串使用 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())
)
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()
就足够了。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。