[Tutor] Conflicted [Strings are immutable]
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sat, 6 Apr 2002 22:27:42 -0800 (PST)
On Sat, 6 Apr 2002, Eve Kotyk wrote:
>
> > > I am however not quite clear as to why the whole line is being
> > > replace rather than just the string requested. >
> >
> > >>> s = 'My name is mud'
> > >>> s.replace('mud', 'Sean')
> > 'My name is Sean'
> > >>> s
> > 'My name is mud'
>
> Ok, perhaps I'm being a little dim but if I do
>
> s = 'Spam is not ham'
> s.replace('Spam', '')
> and write it to a new file, should I not get 'is not ham'?
Strings are 'immutable' in Python --- they don't change. Whenever we do
manipulations on strings, Python creates whole new strings and doesn't
modify the old ones.
It helps if we try your example in the interpreter:
###
>>> s = "Spam is not ham"
>>> s.replace('Spam', '')
' is not ham'
###
Up to this point, what we're seeing is that the expression:
s.replace('Spam', '')
is giving back to us the string that we're expecting. However, this does
not change what 's' itself contains:
###
>>> s
'Spam is not ham'
###
What you probably want to do is capture the string that the replace()
gives in another variable. Here's an example:
###
>>> s_without_spam = s.replace('Spam', '')
>>> s_without_spam
' is not ham'
>>> s
'Spam is not ham'
###
The 's_without_spam' is something you can write to your file. If we want
to make it look like s is being changed itself, we can just reuse 's' as
our variable:
###
>>> s
'Spam is not ham'
>>> s = s.replace(' ', '/')
>>> s
'Spam/is/not/ham'
###
Python strings are designed with this sense of immutability in them, just
like numbers. If we multiply 3 and 4:
###
>>> 3 * 4
12
###
... this doesn't "hurt" 3 or 4 or make any changes to them. Immutability
with strings is the same idea:
###
>>> "three" * 4
'threethreethreethree'
###
Please feel free to ask more questions about this; it's a somewhat subtle
issue but important to understand. Good luck!