Check presence of vowels in a string

前端 未结 6 1097
温柔的废话
温柔的废话 2020-12-02 01:54

I need to check whether a vowel is present in a word. If it is, an operation should be carried out on the word say op(word). I want to avoid a for loop because

相关标签:
6条回答
  • 2020-12-02 01:57

    You can avoid the for loop using a set intersection

    if set('aeiou').intersection(word.lower()):
    
    0 讨论(0)
  • 2020-12-02 02:01
    def vowelz(a):
            vowels = ["a", "e", "i", "o", "u"]
            vowel = False
            for vowell in vowels:
                    if vowell in a:
                            vowel = True
            print vowel
    vowelz(raw_input("Enter a word:"))
    
    0 讨论(0)
  • 2020-12-02 02:02
    vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
    if any(char in vowels for char in word):
       ...
    

    Note: This is better because it short circuits, as soon as it finds the vowel in the word. So, it doesn't have to check all the characters unless there are no vowels in the string.

    Edit: Ran a timeit test and found that, @falsetru's answer is extremely fast, but with few optimizations, the re version beats everything else.

    import re
    
    vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
    pattern = re.compile("[AEIOUaeiou]")
    
    def intersection():
        return bool(vowels.intersection("TWYNDYLLYNGS"))
    
    def any_version():
        return any(char in vowels for char in "TWYNDYLLYNGS")
    
    def re_version():
        return bool(pattern.search("TWYNDYLLYNGS"))
    
    def disjoint():
        return vowels.isdisjoint("TWYNDYLLYNGS")
    
    from timeit import timeit
    
    print timeit("intersection()", "from __main__ import intersection, vowels")
    print timeit("any_version()", "from __main__ import any_version, vowels")
    print timeit("re_version()", "from __main__ import re_version, vowels")
    print timeit("disjoint()", "from __main__ import disjoint, vowels")
    
    0 讨论(0)
  • 2020-12-02 02:09

    Using set.isdisjoint (This method returns as soon as it found match):

    >>> vowels = set('aeiou') # set('aeiouAEIOU') if you want case-insensitivty
    >>> not vowels.isdisjoint('bcd')
    False
    >>> not vowels.isdisjoint('hello')
    True
    
    0 讨论(0)
  • 2020-12-02 02:18

    Or you could just do this. It's very simple.

    line = input('Enter text: ')
    frequency = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
    for i in line:
        if i in 'aeiou':
            frequency[character] = frequency[character] + 1
    for vowel in 'aeiou':
        print(vowel + ': ' + str(frequency[vowel]))
    
    0 讨论(0)
  • 2020-12-02 02:20

    You could use regex.

    import re
    
    if re.search('[AEIOU]', word, flags=re.I):
        # contains vowels
    else:
        # does not
    
    0 讨论(0)
提交回复
热议问题