[Numpy-discussion] string replace
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
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?
> The University of Edinburgh is a charitable body, registered in
> Scotland, with registration number SC005336.
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion