pythonassign

why i get an assigning error in this code


I wrote "pig_latin" code as below. In Pig Latin, if a word begins with a consonant, the speaker removes this letter and puts it at the end, followed by “ay.” For example, “pig” becomes “igpay” and “latin” becomes “atinlay.”

text = " I am a programmer"
text2 = text.split() #['I', 'am', 'a', 'programmer'] 
text3 = ""
end = text2[1:]
start = text2[0]
for i in text2:
    text3 = end + start
print(text3)

I have no idea why this error occurs:

text3 = end + start
TypeError: can only concatenate list (not "str") to list

Solution

  • If you want to append 'ay' at the end of all words that starts with a consonant, you have to Iterate through each word and replace the letters.

    text = " I am a programmer"
    text2 = text.split() #['I', 'am', 'a', 'programmer'] 
    text3 = ""
    
    for i in text2:
        # check for consonant
        others = i[1:]
        others  =''.join(others)
        text3 = text3 + others + i[0] + 'ay '
    print(text3)
    

    If you want to do this for the whole sentence, you can skip the iteration. logic applies the same.