Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'str' object does not support item assignment

Tags:

python

string

I would like to read some characters from a string s1 and put it into another string s2.

However, assigning to s2[j] gives an error:

s2[j] = s1[i]  # TypeError: 'str' object does not support item assignment 

In C, this works:

int i = j = 0; while (s1[i] != '\0')     s2[j++] = s1[i++]; 

My attempt in Python:

s1 = "Hello World" s2 = "" j = 0  for i in range(len(s1)):     s2[j] = s1[i]     j = j + 1 
like image 994
Rasmi Ranjan Nayak Avatar asked May 17 '12 07:05

Rasmi Ranjan Nayak


People also ask

What does it mean by STR object does not support item assignment?

The Python "TypeError: 'str' object does not support item assignment" occurs when we try to modify a character in a string. Strings are immutable in Python, so we have to convert the string to a list, replace the list item and join the list elements into a string.

Which object does not support item assignment in Python?

When you run the code below, Python will throw the runtime exception TypeError: 'str' object does not support item assignment . This happens because in Python strings are immutable, and can't be changed in place.

How do I fix TypeError int object does not support item assignment?

Conclusion # The Python "TypeError: 'int' object does not support item assignment" occurs when we try to assign a value to an integer using square brackets. To solve the error, correct the assignment or the accessor, as we can't mutate an integer value.

How do I fix str object is not callable in Python?

The result was the TypeError: 'str' object is not callable error. This is happening because we are using a variable name that the compiler already recognizes as something different. To fix this, you can rename the variable to a something that isn't a predefined keyword in Python. Now the code works perfectly.


2 Answers

The other answers are correct, but you can, of course, do something like:

>>> str1 = "mystring" >>> list1 = list(str1) >>> list1[5] = 'u' >>> str1 = ''.join(list1) >>> print(str1) mystrung >>> type(str1) <type 'str'> 

if you really want to.

like image 189
Crowman Avatar answered Oct 09 '22 20:10

Crowman


In Python, strings are immutable, so you can't change their characters in-place.

You can, however, do the following:

for c in s1:     s2 += c 

The reasons this works is that it's a shortcut for:

for c in s1:     s2 = s2 + c 

The above creates a new string with each iteration, and stores the reference to that new string in s2.

like image 40
NPE Avatar answered Oct 09 '22 22:10

NPE