Skip to content Skip to sidebar Skip to footer

How To Check If A String Contains A String From A List?

I want to check if a string the user inputted contains one of the strings in a list. I know how to check if the string contains one string but I want to know how to check if a stri

Solution 1:

Using any:

>>> vowels = 'a', 'e', 'i', 'o', 'u'

>>> s = 'cat'
>>> any(ch in vowels for ch in s)
True
>>> s = 'pyth-n'
>>> any(ch in vowels for ch in s)
False

Solution 2:

>>> vowels = set(['a', 'e', 'i', 'o', 'u'])
>>> inp = "foobar"
>>> bool(vowels.intersection(inp))
True
>>> bool(vowels.intersection('qwty'))
False

Solution 3:

This is the basic logic you want:

def string_checker(user_input_string, vowels):
    for i in vowels:
       if i in user_input_string:
          return 'Found it'
    return 'Sorry grashooper :('

print string_checker('Hello',('a','e','i','o','u'))

The short cut way to do this is by using the built-in any() method; which will return true if any of the items in it returns a truth value.

Here is how it would work:

any(i in user_input_string for i in vowels)

The difference is that instead of returning a custom string, this method will return True or False; we can use it the same way in our loop:

if any(i in user_input_string for i in vowels):
    print('Found it!')
else:
    print('Oh noes! No vowels for you!')

Solution 4:

Checking the strings sequentially works, but if it's too inefficient for your case, you can use Aho-Corasick algorithm.


Solution 5:

You can use this syntax

if myItem in list:
# do something

also look at the functions:

http://docs.python.org/2/library/functions.html


Post a Comment for "How To Check If A String Contains A String From A List?"