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, 2022 in Python by Rahul
• 9,680 points
1,382 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, 2022 by Aditya
• 7,680 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,840 points
21,468 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
1,653 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, 2022 in Python by Rahul
• 9,680 points
1,980 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 4,486 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, 2022 in Python by Aditya
• 7,680 points
2,499 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, 2022 in Python by Aditya
• 7,680 points
3,478 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