Reputation: 125
I am starting out with programming, teaching myself Python 3.4.3. I have a question with regards to a pig Latin translator (seems to be everybody's favorite program to write, and ask questions for).
My code seems to work fine, except when I write a word that has y as the only vowel in it.
def pig_latin(word):
print(word)#test
if word[0] in 'bcdfghjklmnpqrstvwxyz':
i = 0
print(word[i]) #test
while word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
word = word[i:] + word[:i] + 'ay'
elif word[0] in 'aeiou':
word += 'way'
return word
def main():
sentence = input('Enter a phrase to convert to pig latin: ')
word = ''
pig_sentence = ''
i = 0
for i in range(len(sentence)):
if sentence[i] != ' ':
word += sentence[i]
else:
pig_sentence += pig_latin(word) + ' '
word = ''
pig_sentence += pig_latin(word)
print(pig_sentence)
if __name__ == '__main__':
main()
The error I receive is with regards to this line of code:
while word[i] in 'bcdfghjklmnpqrstvwxyz':
and the error reads: IndexError: string index out of range
After playing with a lot of stuff, I am a bit stumped. Any help would be appreciated.
Upvotes: 2
Views: 123
Reputation: 2743
You're trying to access an element of your word
that doesn't exist whenever that loop runs out of letters before it finds a proper vowel.
Try this:
while i < len(word) and word[i] in 'bcdfghjklmnpqrstvwxyz':
Upvotes: 0
Reputation: 3973
Your problem is when there are no vowels in the word. If there are no vowels the following while
loop never stops and you get an IndexError:
while word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
word = word[i:] + word[:i] + 'ay'
To fix this, check that i is less than the length of the word:
while i < len(word) and word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
word = word[i:] + word[:i] + 'ay'
Now with this implementation, the first character does not get moved to the end of the word (i.e. gym turns into gymay), so write a condition for that:
while i < len(word) and word[i] in 'bcdfghjklmnpqrstvwxyz':
i += 1
if i == len(word):
i = 1
word = word[i:] + word[:i] + 'ay'
Upvotes: 1