laur
laur

Reputation: 500

Compare string to multiple strings in Python3

I want to know if there is no text string in the variables. And then compare if there is another text string. The variables results It may contain the following: yes, no or ? I have follow code:

internet = result1
vpn = result2
zetas = result3

values = [internet, vpn, zetas]

    if any(v !== "?" for v in values):
        print("No exist ?")
    if any(v == "no" for v in values):
        print("Exist a NO")
    else:
        print("Good")

especially to see the most elegant way of doing this.

Upvotes: 0

Views: 3104

Answers (3)

Rachel Gallen
Rachel Gallen

Reputation: 28563

I checked if the query you had regarding the question mark in inverted commas would escape detection using an array comparison [x in B for x in A]

#I assigned values to your variables to test
result1 ='?'
result2="no"
result3 = "yes"

internet = result1
vpn = result2
zetas = result3

#created an array with above values in it both in string format and as variable values (appended a number just for test)
A = [internet, 'no', '?', 'yes', vpn, zetas, '8']

#array of sample strings
B = ['?', 'no', 'yes']

exists = [x in B for x in A]
print (exists)

When the results of the comparison printed it gave: [True, True, True, True, True, True, False]. However if there were additional quote marks, e.g. '"?"' , the comparison on this printed as False. (Items in single quotes evaluate the same as double quotes..)

Feel free to run/re-assign values/test etc as you please. (might not be the answer you're looking for but hope it helps)

Upvotes: 0

furas
furas

Reputation: 142641

you can check value in list or value not in list

values = (internet, vpn, zetas)

if "?" not in values:
    print("No exist ?")
if "no"  in values:
    print("Exist a NO")
else:
    print("Good")

Upvotes: 2

gonmrm
gonmrm

Reputation: 89

First it is preferable to pass generator expressions instead of lists for loop feeding.

Secondly, although there can be many ways,, a good way would simply be:

values = (internet, vpn, zetas)
if "?" in (v for v in values):
  print("No exist ?")

Generator expressions save memory and time, not critical for the script in hand but useful for larger chunks of data.

Upvotes: 1

Related Questions