[英]Finding an exact match of the text in list
我想检查列表中的文本是否完全匹配。
lst = ["Hi my name is ", "apple "]
new_lst = [t.strip() for t in lst]
text = input("text: ").lower()
if text in new_lst:
print("True")
else:
print("False")
但是当我输入hi my name is
我得到false
而不是true
。
我怎样才能解决这个问题?
正如@timgeb 所提到的,在 Python 中,字符串相等检查区分大小写。
标准化输入和数据以确保不区分大小写是相当普遍的。 在您的代码中,由于您正在处理lst
的每个元素以删除额外的空格,因此将lst
中的文本也标准化为小写也非常简单。
lst = ["Hi my name is ", "apple "]
new_lst = [t.strip().lower() for t in lst] # using method chaining
# to lowercase the stripped text
# by applying .lower()
text = input("text: ").lower()
if text in new_lst:
print("True")
else:
print("False")
尝试
new_lst = [t.strip().lower() for t in lst]
你可以试试
lst = ["Hi my name is ", "apple "]
new_lst = [t.strip().lower() for t in lst]
text = input("text: ").lower()
print("True" if text.lower() in new_lst else "False")
此代码会将 lst 列表中的所有字符更改为小写,并将输入文本作为小写进行比较,这样,您将获得匹配。
您可以像这样比较时直接剥离和小写:
lst = ["Hi my name is ", "apple "]
text = input("text: ").lower()
if text in [e.strip().lower() for e in lst]:
print("True")
else:
print("False")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.