Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 964
kuthedk Avatar asked Jun 04 '15 19:06

kuthedk


People also ask

How to find vowels in words?

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).


4 Answers

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'):
like image 170
Rahul Tripathi Avatar answered Oct 13 '22 07:10

Rahul Tripathi


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
like image 34
thefourtheye Avatar answered Oct 13 '22 06:10

thefourtheye


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.

like image 40
John Wilson Avatar answered Oct 13 '22 07:10

John Wilson


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'
like image 28
pythondetective Avatar answered Oct 13 '22 05:10

pythondetective