Search and replace.sub(replacement,string[,count=0])不适用于特殊字符

2024-04-25 18:51:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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模式,它是有效的。我不明白为什么代码不起作用。你知道吗


Tags: 字符串代码replothtmlhistregexhistogram
1条回答
网友
1楼 · 发布于 2024-04-25 18:51:53

问题是您正在执行sub方法,而不是捕获 结果。它不会改变字符串的位置。它返回一个新的 字符串。你知道吗

因此(出于上述原因,使用s而不是str):

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

请注意,\n\t也可以工作。你知道吗

相关问题 更多 >