Wierd problem with replace

Peter Hansen peter at engcorp.com
Mon Mar 29 10:46:05 EST 2004


Florian Lindner wrote:
> Hello,
> I've this code:
> 
>     print "Login1:", login
>     login.replace("@","_")
>     print "Login2:", login
> 
> Which produces this output:
> 
>     Login1: tester at root
>     Login2: tester at root
> 
> Why is Login2 still tester at root and not tester_root? I thought that I've
> replaced the @ with _??

Trying it at the command line might be instructive:

 >>> login = 'tester at root'
 >>> print "Login1:", login
Login1: tester at root
 >>> login.replace("@", "_")
'tester_root'
 >>> login
'tester at root'

Strings are immutable.  The call to replace() does not modify
the original string, but returns a new one.  You'll see similar
behaviour with other string methods (or any methods on immutables).

-Peter



More information about the Python-list mailing list