Re: sed to python: replace Q



On Wed, 30 Apr 2008 15:27:36 +1000, Raymond <not-for-mail@xxxxxxxxx> wrote:

For some reason I'm unable to grok Python's string.replace() function.
Just trying to parse a simple IP address, wrapped in square brackets,
from Postfix logs. In sed this is straightforward given:

line = "date process text [ip] more text"

sed -e 's/^.*\[//' -e 's/].*$//'

yet the following Python code does nothing:

line = line.replace('^.*\[', '', 1)
line = line.replace('].*$', '')

str.replace() doesn't support regular expressions.

Try:

import re
p = re.compile("^.*\[")
q = re.compile("].*$")
q.sub('',p.sub('', line))


Is there a decent description of string.replace() somewhere?

Raymond

Section 3.6.1 String Functions

--
Kam-Hung Soh <a href="http://kamhungsoh.com/blog";>Software Salariman</a>
.



Relevant Pages

  • sed to python: replace Q
    ... For some reason I'm unable to grok Python's string.replacefunction. ... Just trying to parse a simple IP address, wrapped in square brackets, ... from Postfix logs. ...
    (comp.lang.python)
  • Re: sed to python: replace Q
    ... Just trying to parse a simple IP address, wrapped in square brackets, ... from Postfix logs. ... yet the following Python code does nothing: ...
    (comp.lang.python)
  • Re: sed to python: replace Q
    ... Raymond wrote: ... Just trying to parse a simple IP address, wrapped in square brackets, ... from Postfix logs. ...
    (comp.lang.python)
  • Re: Problem with "&" charater in xml.
    ... Kirt wrote: ... now in my python code i want to parse this doc and print the directory ... def startElement: ...
    (comp.lang.python)
  • Re: Includeing Python in text files
    ... containig certain section in the form ... I parse the text file and substitute the python code with its result ...
    (comp.lang.python)