Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The code is generating only last part of string? Can anyone help to fix this

def pig_latin(text):  
    say = "ay"
    
    words = text.split()
    print(words)
    
    for word in words:
        x = word[1:] + word[:1] + say
        y = ("".join(x))
    return y
print(pig_latin("hello how are you"))

>Solution :

You keep overwriting y in the loop, you need to save every part, a first solution would be y += "".join(x) but that would give ellohayowhayreaayouyay

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So use a list to keep every modified word, so you can then but a space between them. Also a string slice is a string, you don’t need "".join

def pig_latin(text):
    say = "ay"
    y = []
    for word in text.split():
        x = word[1:] + word[:1] + say
        y.append(x)
    return " ".join(y)


print(pig_latin("hello how are you"))  # ellohay owhay reaay ouyay

Shortened version

def pig_latin(text, say="ay"):
    return " ".join(word[1:] + word[:1] + say for word in text.split())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading