modifying string objects

Gerhard Häring gerhard at bigfoot.de
Thu Jun 13 12:00:48 EDT 2002


Uwe Mayer wrote in comp.lang.python:
> hi,
> 
> strings are immutable in python. so what do i do if i need to pass a 
> function a string as parameter and need it to be modified within the 
> function so that changes are reflected outside of the function body?

You _could_ use a mutable wrapper object, like a custom class or
simply a list, like in:

def add_an_a(swrap):
    swrap[0] = swrap[0] + "a"

x = ["b"]
add_an_a(x)
print x[0]

But it's generally much better to just let the function return the new
value, as in:

def add_an_a(s):
    return s + "a"

print add_an_a("b")

HTH,

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list