Replacing one character of a string in python

后端 未结 5 1115
傲寒
傲寒 2020-12-20 11:35

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

TypeError: \'str\' object does not support item assig

5条回答
  •  死守一世寂寞
    2020-12-20 12:36

    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.

提交回复
热议问题