1

i just want to compare a string with a list of string

if the pattern of letters matching to the list, the i want a simple true as output

see my example below:

a = ["jackpot","guru","otto","name"]
    
    
s = "tttguruugfhghd"


    if s contain in a:
        print("hit")
    else:
        print("no hit")

output should be:

hit (in this case)

i think there is a easy solution, but i didn't find anything yet

ok, now this is working, but now i have a new question:

a = ["jackpot","guru","otto","name"]    
s = "guruu"

if s in a:
    print("hit")
else:
    print("no hit")

if i run this code i get a no hit but i want a hit even if "s" the string is not 100% matching but i contains the pattern

3 Answers3

1

We can traverse the list and check if entries are in the s string; once found, we break the loop:

for seq in a:
    if seq in s:
        print("hit")
        break
else:
    print("no hit")

where we use for with else to detect any hit or not (else is kind of "no-break" here). But any is better:

if any(seq in s for seq in a):
    print("hit")
else:
    print("no hit")

which reads "if any of the seq in the list a is contained in s, then print "hit"; else "no hit"".

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
0

Should be

if s in a:

instead of

if s contain in a:

Also, you have unnecessary indentation.

EDIT, answering question. Then you need to iterate..

a = ["jackpot","guru","otto","name"]

s = "jackpottt"

contains = False

for entry in a:
    if entry in s:
        contains = True
        print("hit")

if not contains:
    print("no hit")
bosowski
  • 124
  • 6
  • thanks for this answer i am not at my final goala = ["jackpot","guru","otto","name"] s = "guruu" if s in a: print("hit") else: print("no hit") in this case i want to see a hit, but how? – pythonbeginner Jul 02 '21 at 20:18
  • See my edit, pretty simple example based on what you had. – bosowski Jul 02 '21 at 20:27
0

I would check each element for the solution.

if len([ a_elem for a_elem in a if a_elem in s]) > 0:
    print("hit")

Above we have a list comprehension that filters the elements of a on the basis of whether or not they exist in s. If the length of the filtered list isn't empty, there is at least one hit.

David Kaftan
  • 1,974
  • 1
  • 12
  • 18