[英]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:\QUAREP\Controlli\12011191\2022-06-29\STL\12011191-92-95-202-203_220701_PR1.g3d')
x = any(mylist)
print (x)
With the print (x) I print, in this case, true.使用 print (x) 我打印,在这种情况下,是真的。 But I want to print 'PR1'.但我想打印'PR1'。 Alternatively for me is useful the index, too.或者对我来说,索引也很有用。 How to do this?这个怎么做? Thank you very much!非常感谢!
Try this out:试试这个:
mylist = ['IP', 'PR1','PR2']
string = 'S:\QUAREP\Controlli\12011191\2022-06-29\STL\12011191-92-95-202-203_220701_PR1.g3d'
print([ele for ele in mylist if(ele in string)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.