How to check if multiple strings exist in another string in Python?

PythonServer Side ProgrammingProgramming

To check if any of the strings in an array exists in another string, you can use the any function. 

example

arr = ['a', 'e', 'i', 'o', 'u']
str = "hello people"
if any(c in str for c in arr):
    print "Found a match"

Output

This will give you the output:

Found a match

Example

Though an overkill, you can also use regex to match the array. For example:

import re
arr = ['a', 'e', 'i', 'o', 'u']
str = "hello people"
if any(re.findall('|'.join(arr), str)):
    print 'Found a match'

Output

This will give you the output:

Found a match
raja
Published on 13-Dec-2017 19:16:31
Advertisements