[Tutor] string formatting question

Karl Pflästerer khp at pflaesterer.de
Fri Apr 7 22:28:28 CEST 2006


On  7 Apr 2006, jjabson at yahoo.com wrote:

> Sorry I didn't make my question clearer. Bascially I
> want to replace this line:
>
> <srm:socket portNumber="138" tcpORudp="UDP"
> address="64.41.134.60"/>
>
> With:
>
> <srm:socket portNumber="2" tcpORudp="TCP"
> address="64.41.134.60"/>
>
> So the regex grouping are that I want to keep
> portNumber= and tcpORudp= and replace the values.
> Which will be varibles in my code. 
>
> The question is more on the string formatting in the
> replace. How do use two %s in one statement? 
>
> i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line)

You could write it simply like that:

Python> s = '<srm:socket portNumber="138" tcpORudp="UDP" address="64.41.134.60"/>'
Python> re.sub('".*?"','"%s"',s,2)
'<srm:socket portNumber="%s" tcpORudp="%s" address="64.41.134.60"/>'
Python> re.sub('".*?"','"%s"',s,2) % ('1000', 'TCP')
'<srm:socket portNumber="1000" tcpORudp="TCP" address="64.41.134.60"/>'

Or you could exploit the fact that you can use a function instead of a
simply string as substitution; in that function you can do really
complicated things.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


More information about the Tutor mailing list