python – How to check if the string contains any word from the list?

Question:

For example, there is a list

words = ["Авто", "Велосипед", "Самолет"]

And for example the line

str = "Быстрый автомобиль"

You need to return True , because there is "auto" in the line

Answer:

using regular expressions, you can do this check without a loop:

In [12]: import re

In [13]: chk_pat = '(?:{})'.format('|'.join(words))

In [14]: chk_pat
Out[14]: '(?:Авто|Велосипед|Самолет)'

In [15]: s = "Быстрый автомобиль"

In [16]: bool(re.search(chk_pat, s, flags=re.I))
Out[16]: True

In [17]: bool(re.search(chk_pat, 'строка', flags=re.I))
Out[17]: False

PS if the list of words of the check is too long 10 + K bytes, then it is probably better not to use such long regular expressions

Scroll to Top