joe wong
joe wong

Reputation: 473

How to simplify the IF statement in Python 3

I have the IF statement as follows:

...
if word.endswith('a') or word.endswith('e') or word.endswith('i') or word.endswith('o') or word.endswith('u'):
...

Here I had to use 4 ORs to cover all the circumstances. Is there anyway I can simplify this? I'm using Python 3.4.

Upvotes: 0

Views: 113

Answers (4)

AKS
AKS

Reputation: 19861

Simply:

>>> "apple"[-1] in 'aeiou'
True
>>> "boy"[-1] in 'aeiou'
False

Upvotes: 1

mhawke
mhawke

Reputation: 87134

word.endswith(c) is just the same as word[-1] == c so:

VOWELS = 'aeiou'

if word[-1] in VOWELS:
    print('{} ends with a vowel'.format(word)

will do. There is no need to construct a list, tuple, set, or other data structure: just test membership in a string, in this case VOWELS.

Upvotes: 0

Hafees Kazhunkil
Hafees Kazhunkil

Reputation: 113

Try

if word[-1] in ['a','e','i','o','u']:

where word[-1] is the last letter

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174834

Use any

>>> word = 'fa'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>> word = 'fe'
>>> any(word.endswith(i) for i in ['a', 'e', 'i', 'o', 'u'])
True
>>> 

Upvotes: 3

Related Questions