我有一个字符串,我想用html代码替换特殊字符。代码如下:
s= '\nAxes.axvline\tAdd a vertical line across the axes.\nAxes.axvspan\tAdd a vertical span (rectangle) across the axes.\nSpectral\nAxes.acorr'
p = re.compile('(\\t)')
s= p.sub('<\span>', s)
p = re.compile('(\\n)')
s = p.sub('<p>', s)
此代码将字符串中的\t
替换为<\\span>
,而不是按代码要求的<\span>
。你知道吗
我已经在regex101.com上测试了regex模式,它是有效的。我不明白为什么代码不起作用。你知道吗
我的目标是将输出用作html代码。“<;\span>;”字符串不能被HTML识别为标记,因此它是无用的。我必须想办法将文本中的\t替换为<;\span>;,而不是替换为<;\span>;。在Python中这是不可能的吗?我之前也发布了一个类似的问题,但是这个问题并没有具体解决我在这里提出的问题,也没有明确我的目标,即将修改后的文本作为HTML代码使用。收到的答复没有正常发挥作用,可能是因为作出答复的人忽视了这些事实。你知道吗
不,它确实有用。只是你打印了它的
repr
。你是在python shell中测试这个的吗?你知道吗在python shell中:
shell使用
repr
函数输出返回值(如果不是None
)。克服 这样,您就可以使用print
函数,它返回None
(因此不会由shell输出),并且 不调用repr
函数。你知道吗注意,在这种情况下,您不需要regex。你只要做一个简单的
replace
:对于正则表达式,应该在字符串前面加上
r
:请注意,如果您不止一次使用compile regex,您可以一步完成
正则表达式是超级强大的。不要放弃!你知道吗
相关问题 更多 >
编程相关推荐