[Tutor] Modify a string multiple times

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Sep 28 19:28:44 CEST 2004



On Tue, 28 Sep 2004, Chad Crabtree wrote:

> >line = 'python and perl are both programming languages.'
> >newstring = re.sub('python','Python',line)
> >newstring2 = re.sub('perl','Perl',newstring)
> >print newstring2
> >
> Yup I think you are making this to hard.
>
> line='python and perl are both programming languages.'
> line=re.sub("python",'Python',line)
> line=re.sub("perl","Perl",.line)
> print line


Hi Tom,

Yes, the '=' operator stands for "assignment", not "equality".  The
difference is that assignment is an action, and timing's involved.


The way that Python deals with assignments:

   left_hand_side = right_hand_side

is to first figure out the value of the right_hand_side, and then set that
value into left_hand_side.


So that's why it's ok to say:

    line = re.sub("python",'Python', line)

because even though "line" appears on both the left hand and right hand
sides, Python doesn't do both sides simultaneously.  Instead, it'll first
compute the substitution string from the expression:

    re.sub("python",'Python', line)

and after it's done computing the value, it'll then plug it right back
into 'line'.


Hope this helps!



More information about the Tutor mailing list