0

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.

joe wong
  • 453
  • 2
  • 9
  • 24

4 Answers4

3

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
>>> 
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • like in someone answer's you may also use `"aeiou"` instead of a list `['a', 'e']` since both list and string are iterables in python – Avinash Raj May 09 '16 at 06:05
2

Try

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

where word[-1] is the last letter

1

Simply:

>>> "apple"[-1] in 'aeiou'
True
>>> "boy"[-1] in 'aeiou'
False
AKS
  • 18,983
  • 3
  • 43
  • 54
0

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138