Skip to content
Advertisement

Find if string contains one of the word in list and print the word it finds

I want to find if one word in list exists in a string and then print the found value. I am able to do this, but only with a true/false output.

mylist = ['IP', 'PR1','PR2']
str=('S:QUAREPControlli120111912022-06-29STL12011191-92-95-202-203_220701_PR1.g3d')
x = any(mylist)
print (x)

With the print (x) I print, in this case, true. But I want to print ‘PR1’. Alternatively for me is useful the index, too. How to do this? Thank you very much!

Advertisement

Answer

Try this out:

mylist = ['IP', 'PR1','PR2']
string = 'S:QUAREPControlli120111912022-06-29STL12011191-92-95-202-203_220701_PR1.g3d'

print([ele for ele in mylist if(ele in string)])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement