I'm trying to check for a vowel as the first character of a word. For my code I currently have this:
if first == 'a' or first == 'e' or first == 'i' or first == 'o' or first == 'u':
I was wondering is there a much better way to do this check or is this the best and most efficient way?
What Are Vowels? In the English language, the letters “a,” “e,” “i,” “o,” “u” and sometimes “y” are called vowels. When you speak, you let out air through your mouth. Vowels make the sounds that come when the air leaving your mouth isn't blocked by anything (like your teeth or your tongue).
You can try like this using the in
:
if first.lower() in 'aeiou':
or better like
if first.lower() in ('a', 'e', 'i', 'o', 'u'):
Better create a set of vowels, like this
>>> vowels = set('aeiouAEIOU')
>>> vowels
set(['a', 'A', 'e', 'i', 'o', 'I', 'u', 'O', 'E', 'U'])
and then check if first
is one of them like this
>>> if first in vowels:
...
Note: The problem with
if first in 'aeiouAEIOU':
approach is, if your input is wrong, for example, if first
is 'ae'
, then the test will fail.
>>> first = 'ae'
>>> first in 'aeiouAEIOU'
True
But ae
is clearly not a vowel.
Improvement:
If it is just a one-time job, where you don't care to create a set beforehand, then you can use if first in 'aeiouAEIOU':
itself, but check the length of first
first, like this
>>> first = 'ae'
>>> len(first) == 1 and first in 'aeiouAEIOU'
False
Here is the regex approach:
from re import match
if match(r'^[aieou]', first):
...
This regular expression will match if the first character of "first" is a vowel.
If your function is returning boolean value then easiest and simplest way will be
`bool(first.lower() in 'aeiou')`
Or
return first.lower() in 'aeiou'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With