My list is a=['Name','Age','Subject'] and I want to search whether an input by the user exists in this list or not.
Let's say the user enters x='name', how do I search for x in this list a (case-insensitively)?
My list is a=['Name','Age','Subject'] and I want to search whether an input by the user exists in this list or not.
Let's say the user enters x='name', how do I search for x in this list a (case-insensitively)?
I think the following code might help you. You have to string
modification methods lower()/upper()
. I used lower here, it changes any case of each character to lower case. e.g. after using 'NaMe'.lower()
to NaMe
changed to `'name''. I changed both the input string and list elements and checked whether the input is in the list. That's all.
Code
a=['Name','Age','Subject']
a = [a.lower() for a in a]
user_input = input("Put the input: ").lower()
if user_input in a:
print("Match")
else:
print("Mismatch")
Output
> Put the input: AGE
> Match
If you want to do a case sensitive search in the list you can do,
x = "name" # input from the user
l = ['Name','Age','Subject']
if x in l:
print("Found a match")
else:
print("No match")
If you want to do a case insensitive search in the list you can do,
x = "name" # input from the user
l = ['Name','Age','Subject']
if x.lower() in list(map(lambda x: x.lower(), l)):
print("Found a match")
else:
print("No match")
You can do as follows Without casting the whole list:
b = input("please enter a string:")
ismatch =b.title() in a
print(ismatch)
>>> please enter a string:
>Age
>>> True
a=['Name','Age','Subject']
if 'Name' in a:
print "yes"