I am trying to check if an item exists in my list, but it has to be exact match. And my code isn't working right.
import sys
fruitlist = str(sys.argv[2:]).upper()
print(sys.argv[1])
print(fruitlist)
if sys.argv[1].strip() in fruitlist:
print(sys.argv[1], 'exact match found in list')
Now if I run it, this is what happens.
$ python3 a.py STRAW apple pear strawberry
STRAW
['APPLE', 'PEAR', 'STRAWBERRY']
STRAW exact match found in list
STRAW isn't really in my list, but because strawberry is in the list, it still says exact match found.
I want this to be false for STRAW and true only for STRAWBERRY
CodePudding user response:
fruitlist is a string, not a list.
fruitlist = str(sys.argv[2:]).upper()
converts the sys.argv
to str
then applies the upper case.
to avoid this you can do this instead:
fruitlist = [x.upper() for x in sys.argv[2:]]
full code:
import sys
fruitlist = [x.upper() for x in sys.argv[2:]]
print(sys.argv[1])
print(fruitlist)
if sys.argv[1].strip() in fruitlist:
print(sys.argv[1], 'exact match found in list')
CodePudding user response:
Your fruitlist
isn't actually a list; it is a string. Here is the correct code, which makes it a list not a string:
import sys
fruitlist = [str(a).upper() for a in sys.argv[2:]]
print(sys.argv[1])
print(fruitlist)
if sys.argv[1].strip() in fruitlist:
print(sys.argv[1], 'exact match found in list')
CodePudding user response:
you convert list to str and then to upper case, you must convert itmes of list to upper case:
import sys
fruitlist = [item.upper() for item in sys.argv[2:]]
if sys.argv[1].strip() in fruitlist:
print(sys.argv[1], 'exact match found in list')
CodePudding user response:
Maybe you could try it this way:
fruitlist = str(sys.argv[2:]).upper()
inp_arg = sys.argv[1]
mask = [f==inp_arg for f in fruitlist]
if_exists = True in mask
if there is any match, the index in mask list would be True, and you can check if True is in mask
CodePudding user response:
You want to use ==
to check for equality:
import sys
term = sys.argv[1].strip().upper()
fruitlist = list(map(str.upper, sys.argv[2:]))
def search(term, lst):
for item in lst:
if item == term:
return True
print(search(term, fruitlist))
Out:
python3 var.py foo bar baz foobar
>>> None
python3 var.py foo bar baz foo
>>> True