[Numpy-discussion] string replace

Eelco Hoogendoorn hoogendoorn.eelco at gmail.com
Mon Apr 21 03:25:57 EDT 2014


Indeed this isn't numpy, and I don't see how your collegues opinions have
bearing on that issue; but anyway..

There isn't a 'python' way to do this, the best method involves some form
of parsing library. Undoubtly there is a one-line regex to do this kind of
thing, but regexes are themselves the antithesis of python.

Here is how id do it, using pyparsing:

from pyparsing import *
line_left = './erfo/restart.ST010.EN0001-EN0090.YYYYMMDDhh'
n1 = Word(nums,exact=3).setParseAction(replaceWith('000'))
n2 = Word(nums,exact=4).setParseAction(replaceWith('0001'))
n3 = Word(nums,exact=4).setParseAction(replaceWith('0092'))
pattern = Literal('ST')+ n1 +'.EN'+n2+'-EN'+n3
print pattern.transformString(line_left)



On Sun, Apr 20, 2014 at 5:25 PM, Siegfried Gonzi
<siegfried.gonzi at ed.ac.uk>wrote:

> Hi all
>
> I know this is not numpy related but a colleague insists the following
> is supposed to work. But it doesn't:
>
> ==
> line_left = './erfo/restart.ST010.EN0001-EN0090.YYYYMMDDhh'
> enafix = 'ST000.EN0001-EN0092'
> line_left = line_left.replace('STYYY.ENXXXX-ENXXXX', enafix)
> print 'line_left',line_left
> ==
>
> [right answer would be: ./erfo/restart.ST000.EN0001-EN0092.YYYYMMDDhh' ]
>
> I think it works in Fortran but not in Python. What would be the easiest
> way to replacing this kind of pattern in a variable lenght string?
>
>
> Thanks,
> Siegfried
>
>
>
> --
> The University of Edinburgh is a charitable body, registered in
> Scotland, with registration number SC005336.
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140421/0f244063/attachment.html>


More information about the NumPy-Discussion mailing list