Search and replace --.sub(replacement, string[, co

2020-05-03 13:41发布

问题:

I am learning Python and Regex and I do some simple exercises. Here I have a string and I want to replace special characters with html code. The code is the following:

str= '\nAxes.hist\tPlot a histogram.\nAxes.hist2d\tMake a 2D histogram plot.\nContours\nAxes.clabel\tLabel a contour plot.\nAxes.contour\tPlot contours.'

p = re.compile('(\\t)')
p.sub('<\span>', str)
p = re.compile('(\\n)')
p.sub('<p>', str)

This code leaves the special characters (\n and \t) unaltered.

I have tested the regex pattern on regex101.com and it works. I can not understand why the code is not working.

回答1:

The problem is that you’re executing the sub method and not capturing the result. It doesn’t change the string in-place. It returns a new string.

Thus (using s instead of str for reasons explained above):

p = re.compile('(\\t)')
s = p.sub('<\span>', s)
p = re.compile('(\\n)')
s = p.sub('<p>', s)

Note that \n and \t will work as well.