-1

I am working in Python right now.

My ch variable, which is the character variable has a character store in it, which has been entered by the user. I also have a string variable (string1) in which I want to add the character without over-writing the string variable.

i.e I want to do string1[i]=ch, where i can be any position.

when i do this in python, it gives an error saying: 'str' object does not support item assignment.

here, string1[i]=ch, is in a while loop.

Is there a proper way of doing this? Please help.

  • 1
    It is impossible to help you without you telling us what you are basically hoping to achieve or without looking at your code – Ofer Sadan Jul 16 '17 at 11:57

1 Answers1

0

str in python is immutable. That means, you can't assign some random value to a specific index.

For example, below is not possible:

a = 'hello'
a[2]= 'X'

There is an workaround.

  • make a list from the str.
  • mutate the specific index you wanted from that list.
  • form a str again from the list.

Like below:

>>> a = 'hello'
>>> tmp_list = list(a)
>>> tmp_list
['h', 'e', 'l', 'l', 'o']
>>> tmp_list[2] = 'X'
>>> tmp_list
['h', 'e', 'X', 'l', 'o']
>>> 
>>> a = ''.join(tmp_list)
>>> a
'heXlo'
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57