String Methods Don't Change ID?

Erik Max Francis max at alcyone.com
Mon Jan 27 18:41:28 EST 2003


Kamilche wrote:

> But now, I'm looking the following example, which modifies a string,
> but the ID doesn't change. Can anyone explain why the built-in string
> methods don't modify the ID?
> 
> >>> quest = 'what is your favorite color?'
> >>> id(quest)
> 10988760
> >>> quest.capitalize()
> 'What is your favorite color?'
> >>> id(quest)
> 10988760
> >>> quest.center(40)
> '      what is your favorite color?      '

This should have been the tip-off as to what was going on.  If the
capitalize method really were changing the original object, then this
centered version should have been capitalized.  It isn't, so the
capitalize "change" didn't take, so therefore what you thought was going
on wasn't.

Not only do capitalize and center not modify their original object, but
_no_ string method (or any other operation for that matter) can; strings
are immutable in Python.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ That it will never come again is what makes life so sweet.
\__/ Emily Dickinson
    Alcyone Systems / http://www.alcyone.com/
 Alcyone Systems, San Jose, California.




More information about the Python-list mailing list