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.

2

4 Answers 4

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
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

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
2

Try

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

where word[-1] is the last letter

Comments

1

Simply:

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.