Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

python - Check presence of vowels in a string

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 I thought of this:

for char in word:
    if char in 'aeiou':
#confused here... 

Please, recommend a method that is low in cost when it comes to execution time. Also, help me correct the above approach too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...