Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python if x in y

Tags:

python

if "test" in ['testtext', 'aaaa', 'texttext']:
    print("yes")
else:
    print("no")

This will always output "no". How can I change this so it outputs "yes" as the word "test" is present in 'testtext' even though it's just a portion of it?


2 Answers

You can use any() builtin function:

if any("test" in w for w in ['testtext', 'aaaa', 'texttext']):
    print("yes")
else:
    print("no")

Prints:

yes
like image 99
Andrej Kesely Avatar answered Sep 04 '26 13:09

Andrej Kesely


you can also try with operator builtin module with operator.contains

txt = ['testtext', 'aaaa', 'texttext']

[operator.contains(i,'test') for i in txt]

output:

[True, False, False]

if u want get word which is true. first convert ur txt file in numpy array then then try this.

txt = np.array(txt)
x = [operator.contains(i,'test') for i in txt]
txt[x] 

output:

array(['testtext'], dtype='<U8')
like image 29
Arjunsai Avatar answered Sep 04 '26 14:09

Arjunsai