[Tutor] string formatting question

Kent Johnson kent37 at tds.net
Fri Apr 7 19:45:28 CEST 2006


Jerome Jabson wrote:
> 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 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list