[Tutor] string formatting question
Jerome Jabson
jjabson at yahoo.com
Fri Apr 7 20:18:18 CEST 2006
Hi Kent,
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)
Thanks again!
> Hello,
>
> I'm trying to replace some strings in a line of
text,
> using some regex functions. My question is: If
there's
> more then one regex grouping I want to replace in
one
> line of a file, how can I use the String Formatting
> operator (%s) in two places?
Hi Jerome,
I don't understand your question. Can you give a
complete example of
the
line from the file and the new line you want to
create?
>
> Here's the line it matches in the file:
>
> <srm:socket portNumber="138" tcpORudp="UDP"
> address="64.41.134.60"/>
>
> Here's the regex:
> m_sock = re.compile('(portNumber=)"\d+"
> (tcpORudp=)"[A-Z]+"')
You have put parentheses around fixed strings, so your
groups will
always be the same. Is that what you want?
>
> My replace should look like this:
> \1 "112" \2 "TCP"
> (obviously "112" and "TCP" would be varibles)
This looks like you want to make the string
portNumber= 112 tcpORudp= TCP
but that doesn't have any variable text from the
original string so I
think I must not understand.
Kent
>
> My problem now is how do I construct the replace
> statement?
> twork = m_sock.sub('\1 %s \2 %s', % port_num %
proto,
> twork)
>
> But of course this does not work! :-( Is there a
> better way to do this? Or am I just doing this all
> wrong?
>
> Thanks in advance!
>
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
More information about the Tutor
mailing list