简体   繁体   English

如何检查字符串是否包含列表中的字符串?

[英]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). 例如,如果我要检查用户的输入以查看其中是否包含元音,那么当我们谈论元音时(a,e,i,o或u)可以有5种不同的选择。 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; 实现此目的的捷径是使用内置的any()方法。 which will return true if any of the items in it returns a truth value . 如果其中任何一项返回真值 ,则返回true。

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 ; 区别在于,此方法将返回TrueFalse ;而不是返回自定义字符串。 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 http://docs.python.org/2/library/functions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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