我正在学习 Python 和 Regex,并做了一些简单的练习。
这里我有一个字符串,我想用 html 代码替换特殊字符。代码如下:
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)
此代码保留特殊字符 (\n
and \t
)不变。
我已经在 regex101.com 上测试了正则表达式模式并且它有效。我不明白为什么代码不起作用。
问题是你正在执行sub
方法而不是捕获
结果。它不会就地更改字符串。它返回一个new
string.
因此(使用s
代替str
由于上述原因):
p = re.compile('(\\t)')
s = p.sub('<\span>', s)
p = re.compile('(\\n)')
s = p.sub('<p>', s)
注意\n
and \t
也会起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)