'str' object does not support item assignment
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
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.
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
.
Python strings are immutable so what you are trying to do in C will be simply impossible in python. You will have to create a new string.
I would like to read some characters from a string and put it into other string.
Then use a string slice:
>>> s1 = 'Hello world!!'
>>> s2 = s1[6:12]
>>> print s2
world!