TypeError: 'str' object does not support item assignment in Python

Dung Do Tien Aug 31 2021 39

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have a small assignment, I want to build some colors from a list color. Like this:

 colors=["Blue", "Green", "Black", "Yellow", "Brown", "Silver"]

def build(s):
    count = 0
    for i in range(0,len(s)):
        s[i]=colors[i]
    return s

print(build("Color"))

But I get an exception TypeError: 'str' object does not support item assignment when I run code above.

 Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(build("Color"))
  File "main.py", line 6, in build
    s[i]=colors[i]
TypeError: 'str' object does not support item assignment

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • D

    David Logacho Aug 31 2021

    Python does not allow you to swap out characters in a string for another one; strings are immutable. What you'll need to do is create a totally different string and return that instead.

    See an example below:

     colors=["Blue", "Green", "Black", "Yellow", "Brown", "Silver"]
    
    def build(s):
        str_color = ""
        for i in range(0,len(s)):
            str_color= str_color + " " + colors[i]
        return str_color
    
    print(build("Color"))

    #OUTPUT

     Blue Green Black Yellow Brown

    Hope it's the answer for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close