How to check if any element of a list is in a string variable in python ?


Example of how to check if any element of a list is in a string variable in python :

Using list comprehension and any

Let's consider the following string variable (called user_agent):

user_agent = 'Mozilla/5.0 (Linux; Android 7.0; SAMSUNG SM-G955U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/5.4 Chrome/51.0.2704.106 Mobile Safari/537.36'

We want to check if any of word in the list:

keywords = ['Mobile','Opera Mini','Android']

are in user_agent.

A solution is to do:

if any(word in user_agent for word in keywords):
    print('Visitor is on mobile device')
else:
    print('Visitor is on desktop')

In this example, we get:

Visitor is on mobile device

see an example of application here

References