Mutable strings

Rob Tillotson rob at
Mon Sep 22 13:59:00 CEST 2003

hjwidmaier at (Hans-Joachim Widmaier) writes:
> Still, I can see a use for mutable strings. Or better, mutable binary
> data, made up of bytes. (where 'byte' is the smallest individually
> addressable memory unit blabla, ... you get the meaning. Just to not
> invite nit-pickers on that term.)
>> "explicit is better than implicit".
> Yes, definitely: Let there be another type.

There already is one: array.  Mutable blocks of bytes (or shorts,
longs, floats, etc.), usable in many places where you might otherwise
use a string (struct.unpack, writing to a file, etc.).  It is not
quite a mutable string, but it does fit the bill for manipulating raw
bytes.  For example, off the top of my head:

  >>> import array
  >>> a = array.array('B','abcdefg')
  >>> a
  array('B', [97, 98, 99, 100, 101, 102, 103])
  >>> a[2:4] = array.array('B','12345')
  >>> a
  array('B', [97, 98, 49, 50, 51, 52, 53, 101, 102, 103])
  >>> a.tostring()

For times when you really need a mutable string, there is always
UserString.MutableString (not quite sure what version this first
appeared in) -- it isn't terribly efficient since it uses a regular
string internally to hold the data, but it gets the job done and if
you really need something faster it would be a fairly simple exercise
to rewrite it using an array instead.


Rob Tillotson  N9MTB  <rob at>

More information about the Python-list mailing list