str object does not support item assignment

0 votes

I would like to read some characters from a string s1 and put it into another string s2. However, assigning to s2[j], it 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 is :

s1 = "Hello World" 
s2 = "" 
j = 0 

for i in range(len(s1)): 
  s2[j] = s1[i] 
  j = j + 1

Feb 22 in Python by Rahul
• 9,680 points
350 views

1 answer to this question.

0 votes

In Python, strings are not very mutable which states that you cannot 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, following which it stores the reference to that new string in s2. Options are always open and you can use something like:
 

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

Hope this answers your question!!

answered Feb 22 by Aditya
• 7,660 points

Related Questions In Python

0 votes
1 answer

TypeError: 'AxesSubplot' object does not support indexing

Hello , If you plot multiple subplots, the plt.subplots() returns ...READ MORE

answered May 7, 2020 in Python by Niroj
• 82,800 points
15,537 views
+1 vote
1 answer

Does python support all the object oriented concepts?

Python is indeed an object oriented programming ...READ MORE

answered May 21, 2019 in Python by Mohammad
• 3,230 points
812 views
0 votes
1 answer

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

After what I observed, you would have ...READ MORE

answered Feb 11 in Python by Rahul
• 9,680 points
686 views
0 votes
1 answer
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 3,126 views
0 votes
1 answer
0 votes
1 answer

DataFrame constructor not properly called! error

You are providing a string representation of ...READ MORE

answered Feb 22 in Python by Aditya
• 7,660 points
1,186 views
0 votes
1 answer

Unsupported operand type(s) for +: 'int' and 'str'

You seem to be trying to train ...READ MORE

answered Feb 23 in Python by Aditya
• 7,660 points
1,378 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP