How do I modify a string in place?
PythonLevel: Intermediate
How do I modify a string in place?
Hints
- Identify object types, mutability and execution order.
- Trace a minimal example: which values and references change?
Answer
You can’t, because strings are immutable. In most situations, you should
simply construct a new string from the various parts you want to assemble
it from. However, if you need an object with the ability to modify in-place
unicode data, try using an io.StringIO object or the array
module:
>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello, world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello, there!'
>>> import array
>>> a = array.array('w', s)
>>> print(a)
array('w', 'Hello, world')
>>> a[0] = 'y'
>>> print(a)
array('w', 'yello, world')
>>> a.tounicode()
'yello, world'
Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0