Python 字符串比较 - 元音

new*_* 21 0 python string compare

我正在尝试编写一个 Python 函数,它将两个字符串作为参数并返回它们是否具有相同的元音(数量无关紧要)。

因此 ('indeed','bed') 应该返回 true,但是 ('indeed','irate') 应该返回 false。

我坚持这个相当可怕的尝试......

def vocalizer(string_a,string_b):
vowels = ['a', 'e', 'i', 'o', 'u']
result = ''
result_2 = ''
for character in string_a:
    if character in vowels:
       result = result + character
       for item in string_b:
            if item in vowels:
               result_2 = result_2 + item
               for vowel in result:
                    if vowel not in list(result_2):
                       return False
                    else:
                       if vowel in list(result_2):
                          return True
Run Code Online (Sandbox Code Playgroud)

hal*_*lex 5

简短而富有表现力:

def keep_only_vowels(s):
    vowels = ('a', 'e', 'i', 'o', 'u')
    return (c for c in s.lower() if c in vowels)

def vocalizer(s1, s2):
    return set(keep_only_vowels(s1)) == set(keep_only_vowels(s2))
Run Code Online (Sandbox Code Playgroud)

  • 只需`return set(c for c in s.lower() if c in 'aeiou')` (2认同)