The objective of this python exercise is to build a function that turns text into pig latin, a simple text transformation that modifies each word by moving the first character to the end and appending "ay" to the end.
For example, python
ends up as ythonpay
.
I actually built this script, but I am confused as to why it is not iterating over all text.split
elements? And why it is only modifying the last element?
def pig_latin(text):
say = ""
# Separate the text into words
words = text.split()
for word in words:
# Create the pig latin word and add it to the list
new_word = word[1:] + word[0] + "ay"
say = "".join(new_word)
# Turn the list back into a phrase
return say
print(pig_latin("hello how are you"))
# Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun"))
# Should be "rogrammingpay niay ythonpay siay unfay"
This section here is why. You only have one new_word variable, so each time this loop runs, it overwrites the previous value. The only value that doesn't get overwritten is the last one, and you end up with a single string.
for word in words:
new_word = word[1:] + word[0] + "ay"
say = "".join(new_word)
Instead, make sure that each new word ends up in a list. The most intuitive way to do it, IMO, is through list comprehension. Below is how you would format it for this, but look up how to do them. Seriously, it's a couple minutes of your time and they'll be one of your best friends as you continue to learn. You can also do the same thing with dictionaries.
pig_latin_text = [word[1:] + word[0] + "ay" for word in words]
say = " ".join(pig_latin)