Chris
Chris

Reputation: 22237

Replacing one character of a string in python

In python, are strings mutable? The line someString[3] = "a" throws the error

TypeError: 'str' object does not support item assignment

I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method to do this in python?

Upvotes: 18

Views: 29032

Answers (6)

Omkar Darves
Omkar Darves

Reputation: 194

Use this:

someString.replace(str(list(someString)[3]),"a")

Upvotes: 1

Hekmatullah Rahmany
Hekmatullah Rahmany

Reputation: 1

Just define a new string equaling to what you want to do with your current string.

a = str.replace(str[n],"")
 return a

Upvotes: -4

Håvard S
Håvard S

Reputation: 23876

Python strings are immutable, which means that they do not support item or slice assignment. You'll have to build a new string using i.e. someString[:3] + 'a' + someString[4:] or some other suitable approach.

Upvotes: 24

JohnMudd
JohnMudd

Reputation: 13813

>>> import ctypes
>>> s = "1234567890"
>>> mutable = ctypes.create_string_buffer(s)
>>> mutable[3] = "a"
>>> print mutable.value
123a567890

Upvotes: 2

mzz
mzz

Reputation: 3458

In new enough pythons you can also use the builtin bytearray type, which is mutable. See the stdlib documentation. But "new enough" here means 2.6 or up, so that's not necessarily an option.

In older pythons you have to create a fresh str as mentioned above, since those are immutable. That's usually the most readable approach, but sometimes using a different kind of mutable sequence (like a list of characters, or possibly an array.array) makes sense. array.array is a bit clunky though, and usually avoided.

Upvotes: 4

Mark Byers
Mark Byers

Reputation: 837936

Instead of storing your value as a string, you could use a list of characters:

>>> l = list('foobar')
>>> l[3] = 'f'
>>> l[5] = 'n'

Then if you want to convert it back to a string to display it, use this:

>>> ''.join(l)
'foofan'

If you are changing a lot of characters one at a time, this method will be considerably faster than building a new string each time you change a character.

Upvotes: 20

Related Questions