String Methods Don't Change ID?
Peter Hansen
peter at engcorp.com
Mon Jan 27 16:50:43 EST 2003
Kamilche wrote:
>
> I am reading a book on Python, 'Core Python Programming.' They have
> hammered home how when you change a string, or reassign it, the ID
> changes.
>
> 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?
You forgot to prove that the example modifies the string:
> >>> 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? '
> >>> id(quest)
> 10988760
> >>>
Finish up your example by typing "quest" again:
>>> quest
'what is your favorite color?'
Hmm.... neither very centered, nor capitalized, is it? So it hasn't
been modified. ;-)
I like Brett's answer: "strings are immutable (keep repeating that)".
-Peter
More information about the Python-list
mailing list