Is there a better way to check vowels in the first position of a word?

I am trying to check a vowel as the first character of a word. For my code, I currently have the following:

if first == 'a' or first == 'e' or first == 'i' or first == 'o' or first == 'u': 

I was wondering if there is a better way to do this check or is this the best and most efficient way?

+7
python string
source share
4 answers

You can try this using in :

 if first.lower() in 'aeiou': 

or better than

 if first.lower() in ('a', 'e', 'i', 'o', 'u'): 
+15
source share

Better create a set of vowels, for example

 >>> vowels = set('aeiouAEIOU') >>> vowels set(['a', 'A', 'e', 'i', 'o', 'I', 'u', 'O', 'E', 'U']) 

and then check if first one of them, like this one

 >>> if first in vowels: ... 

Note. A problem with

 if first in 'aeiouAEIOU': 
An approach

is that if your input is incorrect, for example, if first is 'ae' , then the test will fail.

 >>> first = 'ae' >>> first in 'aeiouAEIOU' True 

But ae clearly not a vowel.


Improvement:

If this is just a one-time job in which you do not want to create a set in advance, you can use if first in 'aeiouAEIOU': yourself, but first check the length of first , like this

 >>> first = 'ae' >>> len(first) == 1 and first in 'aeiouAEIOU' False 
+7
source share

Here is a regex approach:

 from re import match if match(r'^[aieou]', first): ... 

This regular expression will match if the first "first" is a vowel.

+1
source share

If your function returns a boolean, then the easiest and easiest way would be

 `bool(first.lower() in 'aeiou')` 

or

 return first.lower() in 'aeiou' 
+1
source share

All Articles