Austin Z. Henley Associate Teaching Professor Carnegie Mellon University The fastest way to detect a vowel in a string 6/13/2025 I was nerdsniped recently: What is the best way to detect if a string has a vowel in it? This is trivial, right? But as I started getting into it, I realized there is much more to this. I challenged myself to come up with as many ways to detect a vowel as possible. I even asked a few friends to give it a go. Which is the fastest? Which should never be used? Which is the most clever? This post involves 11 different methods of detecting a vowel, algorithmic analysis, dissembling Python bytecode, inspecting the CPython implementation, and even looking at compiled regex opcodes. Let's go. def has_vowels(s: str) -> bool: ... This is the function stub I'm filling in. If there is at least one vowel in the input string, return True, otherwise return False. You can find the code from this post on GitHub. Method #1: For loop I started with the naive approach: def has_vowel(s): for c in s.lower(): if c in "aeiou": return True return False This is reasonable, readable, and probably without performance issues. Except it does bother me that we are calling lower() which will always create a copy (appending to a string will sometimes mutate it in place but lower does not). We can fix it easily: def has_vowel(s): for c in s: if c in "aeiouAEIOU": return True return False Method #2: For loop, C-style It is really just a more Pythonic form of: def has_vowel(s): for c in s.lower(): if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u': return True return False Method #3: Nested for loop And if we want to be exhaustive, then we should try a nested for loop: def has_vowel(s): vowels = "aeiouAEIOU" for c in s: for v in vowels: if c == v: return True return False Method #4: Set intersection Time to get interesting. Here is my favorite solution that I thought of: def has_vowel(s): return set(s) & set("aeiouAEIOU") It is short, clean, and a little bit clever....
First seen: 2025-06-13 18:54
Last seen: 2025-06-13 18:54