0

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

  • 3
    Does this answer your question? [Is there a short contains function for lists?](https://stackoverflow.com/questions/12934190/is-there-a-short-contains-function-for-lists) – kelvin Nov 19 '20 at 06:35
  • `x in list` It is case sensitive. `x.casefold() in list` it is case insensitive. – Shadowcoder Nov 19 '20 at 06:36
  • 1
    @Shadowcodder no, only if the items in `list` are also casefolded. The example has mixed case. – Mark Tolonen Nov 20 '20 at 06:55

5 Answers5

0

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 NaMechanged 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
KittoMi
  • 411
  • 5
  • 19
0

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")
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
0

Maybe this is what you need:

a = ['Name','Age','Subject']
x = input('').title()
b = x in a
print(b)
Frodon
  • 3,684
  • 1
  • 16
  • 33
Tony
  • 266
  • 1
  • 11
0

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
adir abargil
  • 5,495
  • 3
  • 19
  • 29
0
a=['Name','Age','Subject']
if 'Name' in a:
    print "yes"
Danoram
  • 8,132
  • 12
  • 51
  • 71
Aman Raheja
  • 615
  • 7
  • 16