Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

python - I don't understand why my script is not iterating through all string.split elements?

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...