18

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?

Chris
  • 21,549
  • 25
  • 71
  • 99
  • I have a binary string and on certain conditions, I want to flip a specific 0 to 1. – Chris Jan 29 '10 at 21:19
  • But generally, I'd want to flip a specific letter x to y. Right now I'm dealing with binary strings but it's a general inquiry – Chris Jan 29 '10 at 21:19
  • Another tip: If you're doing "binary strings", i.e. strings consisting of only 1s and 0s, check out a library like BitVector, which is faster and more convenient for bit vector manipulation. Also, see a question on bit vectors in Python at http://stackoverflow.com/questions/2147848/how-do-i-represent-and-work-with-n-bit-vectors-in-python/2147873#2147873 – Håvard S Jan 29 '10 at 21:21

6 Answers6

24

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.

Håvard S
  • 23,244
  • 8
  • 61
  • 72
19

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
4

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.

mzz
  • 3,338
  • 1
  • 14
  • 6
2
>>> import ctypes
>>> s = "1234567890"
>>> mutable = ctypes.create_string_buffer(s)
>>> mutable[3] = "a"
>>> print mutable.value
123a567890
JohnMudd
  • 13,607
  • 2
  • 26
  • 24
0

Use this:

someString.replace(str(list(someString)[3]),"a")
Omkar Darves
  • 164
  • 1
  • 5
-3

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

a = str.replace(str[n],"")
 return a
iknow
  • 8,358
  • 12
  • 41
  • 68
  • This will remove all instances of whichever character is the `n`th character in the string. Also, you shouldn't name your variables after Python builtins (`str` in this case) – Boris Verkhovskiy Sep 10 '20 at 07:27