Modify a string's value

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Jul 15 10:14:58 EDT 2008


Sebastian:
> I've heard that a 'str' object is immutable. But is there *any* way to
> modify a string's internal value?

No, but you can use other kind of things:

>>> s = "hello"
>>> sl = list(s)
>>> sl[1] = "a"
>>> sl
['h', 'a', 'l', 'l', 'o']
>>> "".join(sl)
'hallo'
>>> from array import array
>>> sa = array("c", s)
>>> sa
array('c', 'hello')
>>> sa[1] = "a"
>>> sa
array('c', 'hallo')
>>> sa.tostring()
'hallo'

Bye,
bearophile



More information about the Python-list mailing list