[Numpy-discussion] string replace
robert.kern at gmail.com
Sun Apr 20 11:58:53 EDT 2014
On Sun, Apr 20, 2014 at 4: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?
Your colleague is incorrect. There is nothing in Python that would
take a pattern like that (with Xs and Ys as the wildcards) and do a
replacement. The `str.replace()` method only does exact replacements.
You need to use regular expressions here.
line_left = './erfo/restart.ST010.EN0001-EN0090.YYYYMMDDhh'
enafix = 'ST000.EN0001-EN0092'
line_left = re.sub(r'ST\d\d\d\.EN\d\d\d\d-EN\d\d\d\d',
I will leave the reading about constructing correct regular
expressions to you, but if you try my example code, please note that
every character is precisely important.
More information about the NumPy-Discussion