简体   繁体   中英

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 string contains either this string, or that string, or another string.

For example, if I am checking the user's input to see if it contains a vowel.. there can be 5 different choices when we're talking about vowels (a, e, i, o, or u). How can I check to see if the string the user inputted has one of those?

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
>>> vowels = set(['a', 'e', 'i', 'o', 'u'])
>>> inp = "foobar"
>>> bool(vowels.intersection(inp))
True
>>> bool(vowels.intersection('qwty'))
False

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!')

按顺序检查字符串是可行的,但是如果对于您的情况而言效率太低,则可以使用Aho-Corasick算法

You can use this syntax

if myItem in list:
# do something

also look at the functions:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM