[Tutor] string formatting question
kent37 at tds.net
Fri Apr 7 19:45:28 CEST 2006
Jerome Jabson wrote:
> 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?
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"
> Here's the regex:
> m_sock = re.compile('(portNumber=)"\d+"
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.
> My problem now is how do I construct the replace
> twork = m_sock.sub('\1 %s \2 %s', % port_num % proto,
> But of course this does not work! :-( Is there a
> better way to do this? Or am I just doing this all
> Thanks in advance!
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> Tutor maillist - Tutor at python.org
More information about the Tutor