17

How do I modify a single character in a string, in Python? Something like:

 a = "hello"
 a[2] = "m"

'str' object does not support item assignment.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Shane
  • 4,875
  • 12
  • 49
  • 87
  • possible duplicate of [Change one character in a string in Python?](http://stackoverflow.com/questions/1228299/change-one-character-in-a-string-in-python) – Wolf Mar 02 '15 at 13:54

4 Answers4

15

Strings are immutable in Python. You can use a list of characters instead:

a = list("hello")

When you want to display the result use ''.join(a):

a[2] = 'm'
print ''.join(a)
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
12

In python, string are immutable. If you want to change a single character, you'll have to use slicing:

a = "hello"
a = a[:2] + "m" + a[3:]
JoshD
  • 12,490
  • 3
  • 42
  • 53
  • 1
    I suppose this would cost more memory if it's a really big string since you have to join three other strings together to form a new string, right? – Shane Oct 05 '10 at 05:27
  • Oh, yeah! If you need to do a whole bunch of these type of manipulations, it's best to use a list of characters. Unless you happen to already have a string and just happen to want to change one character. Even then, it's probably faster to create and modify a list. – JoshD Oct 05 '10 at 05:29
  • @Shane: See @detly's answer below for a simple example. – Manoj Govindan Oct 05 '10 at 05:33
8

Try constructing a list from it. When you pass an iterable into a list constructor, it will turn it into a list (this is a bit of an oversimplification, but usually works).

a = list("hello")
a[2] = m

You can then join it back up with ''.join(a).

detly
  • 29,332
  • 18
  • 93
  • 152
3

It's because strings in python are immutable.

Coding District
  • 11,901
  • 4
  • 26
  • 30