On Sun, Apr 20, 2014 at 4:25 PM, Siegfried Gonzi <siegfried.go...@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. https://docs.python.org/2/library/stdtypes.html#str.replace You need to use regular expressions here. https://docs.python.org/2/library/re.html ``` import re 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', enafix, line_left) print 'line_left',line_left ``` 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. -- Robert Kern _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion