简体   繁体   中英

Finding an exact match of the text in list

I want to check if there is an exact match of the text in a 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")

But when I input hi my name is

I get false instead of true .
How can I fix this?

As alluded to by @timgeb, in Python string equality checks are case sensitive.

It is fairly commonplace to normalize both the inputs and the data to ensure that case sensitivity is not a problem. In your code, since you are processing each element of the lst to remove extra spaces, it is pretty straightforward to also normalize the text in your lst to be lowercase as well.

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")

Try

new_lst = [t.strip().lower() for t in lst]

You can try

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")

This code will change all the characters in the lst list to lower and will compare the input text as lower case and by that, you will get a match.

You can strip and lowercase directly while comparing like this:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM