我想在列表中找到 Andy 。 Andy 在字符串中以大写或小写形式出现,程序应返回True
String1 ='Andy is an awesome bowler'
String2 ='andy is an awesome bowler'
String3 ='ANDY is an awesome bowler'
我这样做
if 'Andy' in String1:
print ('success')
else:
print("Nothing")
但它仅适用于Andy
,不适用于andy
或ANDY
。我不想使用Pattern
匹配。通过使用lower()
,Andy
可以转换为小写,但我需要同时忽略较低和大写。可能吗?
答案 0 :(得分:3)
您可以先将字符串转换为大写或小写:
String1 ='Andy is an awesome bowler'
String2 ='andy is an awesome bowler'
String3 ='ANDY is an awesome bowler'
if 'andy' in String1.lower(): # or this could be if 'ANDY' in String1.upper():
print('success')
else:
print('Nothing')
答案 1 :(得分:1)
如果您确定字符串仅包含ascii字符,请使用以下方法:
if 'andy' in string1.lower():
do something
如果你的比较字符串涉及unicodedata:
import unicodedata
def normalize_caseless(text):
return unicodedata.normalize("any_string", text.casefold())
def caseless_equal(left, right):
return normalize_caseless(left) == normalize_caseless(right)