Search and replace.sub(replacement,string[,count=0])不替换特殊字符\

2024-09-29 21:24:32 发布

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

我有一个字符串,我想用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代码使用。收到的答复没有正常发挥作用,可能是因为作出答复的人忽视了这些事实。你知道吗


Tags: the字符串代码ltgtre目标html
1条回答
网友
1楼 · 发布于 2024-09-29 21:24:32

不,它确实有用。只是你打印了它的repr。你是在python shell中测试这个的吗?你知道吗

在python shell中:

>>> '\\'
'\\'
>>> print('\\')
\
>>> print(repr('\\'))
'\\'
>>>

shell使用repr函数输出返回值(如果不是None)。克服 这样,您就可以使用print函数,它返回None(因此不会由shell输出),并且 不调用repr函数。你知道吗

注意,在这种情况下,您不需要regex。你只要做一个简单的replace

s = s.replace('\n', '<p>').replace('\t', '<\span>')

对于正则表达式,应该在字符串前面加上r

compiled_regex = re.compile(r'[a-z]+\s?') # for example
matchobj = compiled_regex.search('in this normal string')
othermatchobj = compiled_regex.search('in this other string')

请注意,如果您不止一次使用compile regex,您可以一步完成

matchobj = re.search(r'[a-z]+\s?', '<- the pattern -> the string to search in')

正则表达式是超级强大的。不要放弃!你知道吗

相关问题 更多 >

    热门问题