我正在学习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
和\t
)不变。你知道吗
我已经在regex101.com上测试了regex模式,它是有效的。我不明白为什么代码不起作用。你知道吗
问题是您正在执行
sub
方法,而不是捕获 结果。它不会改变字符串的位置。它返回一个新的 字符串。你知道吗因此(出于上述原因,使用
s
而不是str
):请注意,
\n
和\t
也可以工作。你知道吗相关问题 更多 >
编程相关推荐