【发布时间】:2017-01-22 16:56:38
【问题描述】:
我正在学习 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 上测试了正则表达式模式,它可以工作。我不明白为什么代码不起作用。
【问题讨论】:
-
您是否尝试过不转义小车和制表符?它没有在您的字符串中转义。另外,永远不要使用
str作为变量名。 -
至少,不要在 Python 中重新定义
str,它是标准类型的名称。可以在 C 中使用str作为变量名。 -
对正则表达式使用
r'raw strings',否则反斜杠会给你带来无穷无尽的麻烦。