0

I am constructing a chatbot that rhymes in Python. Is it possible to identify the last vowel (and all the letters after that vowel) in a random word and then append those letters to another string without having to go through all the possible letters one by one (like in the following example)

lastLetters = ''    # String we want to append the letters to

if user_answer.endswith("a")
    lastLetters.append("a")

else if user_answer.endswith("b")
    lastLetters.append("b")

Like if the word was right we’d want to get ”ight”

deceze
  • 510,633
  • 85
  • 743
  • 889

1 Answers1

0

You need to find the last index of a vowel, for that you could do something like this (a bit fancy):

s = input("Enter the word: ") # You can do this to get user input
last_index = len(s) - next((i for i, e in enumerate(reversed(s), 1) if e in "aeiou"), -1)
result = s[last_index:]
print(result)

Output

ight

An alternative using regex:

import re

s = "right"
last_index = -1
match = re.search("[aeiou][^aeiou]*$", s)
if match:
    last_index = match.start()

result = s[last_index:]
print(result)

The pattern [aeiou][^aeiou]*$ means match a vowel followed by possibly several characters that are not a vowel ([^aeiou] means not a vowel, the sign ^ inside brackets means negation in regex) until the end of the string. So basically match the last vowel. Notice this assumes a string compose only of consonants and vowels.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76