Converting a sentence to piglatin in Python [duplicate]

I have to write a program in Python that will convert sentence into pig Latin. Pig Latin is loosely defined as taking the first letter of each word, putting it at the end of the word, and adding "ay" to the end of each word. I can't figure out how to separate the first letter from each word in the string much less add it to the end.I assume once I get it removed there's a way to concatenate it to the new word then concatenate "ay" as well. I'm extremely lost here. After tons of trial and error This is all I have, and even this doesn't seem to be working right. Any help is much appreciated.

def main(): sentence = input('Type what you would like translated into pig-latin and press ENTER: ') sentence_list = sentence.split() for part in sentence_list: first_letter = part[0] main() 
4

2 Answers

Here is the code:

def main(): lst = ['sh', 'gl', 'ch', 'ph', 'tr', 'br', 'fr', 'bl', 'gr', 'st', 'sl', 'cl', 'pl', 'fl'] sentence = input('Type what you would like translated into pig-latin and press ENTER: ') sentence = sentence.split() for k in range(len(sentence)): i = sentence[k] if i[0] in ['a', 'e', 'i', 'o', 'u']: sentence[k] = i+'ay' elif t(i) in lst: sentence[k] = i[2:]+i[:2]+'ay' elif i.isalpha() == False: sentence[k] = i else: sentence[k] = i[1:]+i[0]+'ay' return ' '.join(sentence) def t(str): return str[0]+str[1] if __name__ == "__main__": x = main() print(x) 

Runs as:

bash-3.2$ python3 pig.py Type what you would like translated into pig-latin and press ENTER: my gloves are warm ymay ovesglay areay armway bash-3.2$ 

This code uses the logic found here.

Here is a quick one

def main(): words = str(input("Input Sentence:")).split() for word in words: print(word[1:] + word[0] + "ay", end = " ") print () main() 

A better solution would probably use list comprehension so you could actually use the output, but this does what you asked.

EDIT: This works for python3.x If you want it to work for python2 you are going to have a bit more fun. Just add the strings together for each word, then print the result string.

2

You Might Also Like