Reputation: 57
I want to be able to search a string for characters in different lists.
For example:
list1=['a']
list2=['b']
If a user enters in 'a' for example. Python should print 'list1'
However, if the user input was 'ab', then Python should print list1 and list2
Right now i'm trying to use this function to query the list, but I have to query each list in two separate if statements, like this.
def char_search(input_str):
for char in input_str:
if char in list1:
print("lower")
if char in list2:
print("Upper")
Upvotes: 0
Views: 533
Reputation: 1602
So, you have some lists:
list1 = [ ... ]
list2 = [ ... ]
...
First you need to be able to collect all that lists together, and then check if each list contains specified item:
for lst in list1, list2, list3:
if mychar in lst:
print(lst)
break
else:
print('Specified lists do not contain', mychar)
Note, that it stops as soon as finds item in one of lists. And also, it doesn't print list's name -- if you want it to, you'll need to make list named like:
class NamedList(list):
def __init__(self, *args, name=None, **kwargs):
self.name = name
super().__init__(*args, **kwargs)
def __str__(self): # only if you need that specific use
if self.name is not None:
return str(self.name)
return super().__str__()
# Then use as follows
std = NamedList(['ISO', 'GOST', 'etc'], name='Standards')
sizes = NamedList(['A4', 'Letter'], name='Paper sizes')
smthng = 'Letter'
for nlst in std, sizes:
if smthng in nlst:
print(nlst) # gives you 'Paper sizes'
Correction: for python 2.x/3.x compatible, use this
Upvotes: 0
Reputation: 862
list1 = ['a']
list2 = ['b']
if (input[0] in list1 or input[1] in list1) and (input[0] in list2 or input[1] in list2):
print "Choice listed"
This works if you want to check that both characters are in at least one list. For more input characters you can add some simple loop logic
Upvotes: 2
Reputation: 21
Example
list_1 = ['a', 'b', 'c']
list_2 = ['d', 'e', 'f']
input = 'b'
if input in list_1:
print "list1"
if input in list_2:
print "list2"
The output will be "list1"
Upvotes: 2
Reputation: 547
choice = input("choose a letter")
if choice in list1:
print(list1)
elif choice in list2:
print(list2)
else:
print("choice not listed")
Upvotes: 1