简体   繁体   中英

How to check whether a string contains any of a list of characters?

Even a word that contains a vowel when entered outputs "NO VOWELS HERE."? Why. Please assist.

vowels = 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'
I = input("enter your name")
L = list(I)
print(L)
if vowels in L:
    print("your name contains a vowel")
else:
    print("NO VOWELS HERE!")

You have to compare each individual vowel.

vowels = 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'
name = input("enter your name")
if any(vowel in name for vowel in vowels):
    print("your name contains a vowel")
else:
    print("NO VOWELS HERE!")

As you can see in this code name is not transferred to a list. You don't need that because a string is iterable. This means that you could do another change:

vowels = 'aAeEiIoOuU'
name = input("enter your name")
if any(vowel in name for vowel in vowels):
    print("your name contains a vowel")
else:
    print("NO VOWELS HERE!")

An example what happened in your original code:

>>> needle = 'a', 'b'
>>> needle in list('ab')
False

Let's check the values:

>>> needle
('a', 'b')
>>> list('ab')
['a', 'b']

You test if the tuple ('a', 'b') is an element of ['a', 'b'] . As you can see it is not. The elements of the list are 'a' and 'b' . To be True the comparison would have to look like this.

>>> needle in [('a', 'b')]
True

You have to understand that you're comparing the exact tuple, not parts of it.

>>> needle in [('a', 'b', 'c')]
False

You can use the intersection property of set for this:

vowels = set('aeiouAEIOU')
I = set(input("enter your name"))

if len(I & vowels)>0:
    print("your name contains a vowel")
else:
    print("NO VOWELS HERE!")

Explanation:

>>> vowels = set('aeiouAEIOU')
>>> vowels
{'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'}
>>> I = set('John Doe')
>>> I
{' ', 'D', 'J', 'e', 'h', 'n', 'o'}
>>> (vowels & I)
{'e', 'o'}

{'e','o'} present in both strings.

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