Scott Divelbiss
Scott Divelbiss

Reputation: 43

Python Pig Latin Converter (Words that start with consonants)

I am trying to convert a string to pig latin. Most examples online don't take into consideration that if a word starts with multiple consonants, you must move all the consonant to the end (school --> oolschay). My version is currently working with the first letter being a vowel as well as grabbing those words that don't start with a vowel, however, I don't know how to stop it from grabbing each instance of the vowel in the word and not just the first instance.

Here is the code:

pigLatin = input("Convert message to pig latin: ")
wordList = pigLatin.lower().split(" ")
vowels = ['a', 'e', 'i', 'o', 'u']
pigLatin = []
eachWord = []
for word in wordList:
    if word[0] in 'aeiou': #case where vowel is first
        pigLatin.append(word + 'yay')
    if word[0] not in 'aeiou':
        for letter in word:
            if letter in 'aeiou':
                pigLatin.append(word[word.index(letter):] + word[:word.index(letter)] +'ay')


print(" ".join(pigLatin))

Upvotes: 1

Views: 4536

Answers (1)

agillgilla
agillgilla

Reputation: 889

You can add a break statement in the inner for loop that iterates through each individual word. It will jump out of the loop once you find a vowel. Or at least I think that's the problem you're having (your question was a little confusing.)

Try this:

pigLatin = input("Convert message to pig latin: ")
wordList = pigLatin.lower().split(" ")
vowels = ['a', 'e', 'i', 'o', 'u']
pigLatin = []
eachWord = []
for word in wordList:
    if word[0] in 'aeiou': #case where vowel is first
        pigLatin.append(word + 'yay')
    else:
        for letter in word:
            if letter in 'aeiou':
                pigLatin.append(word[word.index(letter):] + word[:word.index(letter)] +'ay')
                break


print(" ".join(pigLatin))

I also made your code style a little better by putting an else instead of if word[0] not in 'aeiou':

Happy Coding!

Upvotes: 1

Related Questions