How do I find the first occurrence of a vowel and move it behind the original word (pig latin)?

markiv189 picture markiv189 · Sep 27, 2016 · Viewed 8.3k times · Source

I need to find the first vowel of a string in python, and I'm a beginner. I'm instructed to move the characters before the first vowel to the end of the word and add '-ay'. For example "big" becomes "ig-bay" and "string" becomes "ing-stray" (piglatin, basically).

This is what I have so far:

def convert(s):

    ssplit = s.split()
    beginning = ""
    for char in ssplit:
        if char in ('a','e','i','o','u'):
            end = ssplit[char:]
            strend = str(end)
        else:
            beginning = beginning + char
    return strend + "-" + beginning + "ay"

I need to find a way to stop the "if" statement from looking for further vowels after finding the first vowel - at least I think it's the problem. Thanks!

Answer

njzk2 picture njzk2 · Sep 27, 2016

Break things down one step at a time.

Your first task is to find the first vowel. Let's do that:

def first_vowel(s):
    for index, char in enumerate(s):
        if char in 'aeiou':
            return index
    raise Error('No vowel found')

Then you need to use that first vowel to split your word:

def convert(s):
    index = first_vowel(s)
    return s[index:] + "-" + s[:index] + 'ay'

Then test it:

print(convert('pig'))
print(convert('string'))

Full code, runnable, is here: https://repl.it/Dijj

The exception handling, for words that have no vowels, is left as an exercise.