搜索和替换 --.sub(replacement, string[, count=0])- 不适用于特殊字符 [英] Search and replace --.sub(replacement, string[, count=0])-does not work with special characters

查看:30
本文介绍了搜索和替换 --.sub(replacement, string[, count=0])- 不适用于特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Python 和 Regex,并做了一些简单的练习.这里我有一个字符串,我想用 html 代码替换特殊字符.代码如下:

I am learning Python and Regex and I do some simple exercises. Here I have a string and I want to replace special characters with html code. The code is the following:

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).

This code leaves the special characters (\n and \t) unaltered.

我已经在 regex101.com 上测试了 regex 模式并且它有效.我不明白为什么代码不起作用.

I have tested the regex pattern on regex101.com and it works. I can not understand why the code is not working.

推荐答案

问题是你正在执行 sub 方法而不是捕获结果.它不会就地更改字符串.它返回一个 new字符串.

The problem is that you’re executing the sub method and not capturing the result. It doesn’t change the string in-place. It returns a new string.

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

Thus (using s instead of str for reasons explained above):

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

请注意,\n\t 也能正常工作.

Note that \n and \t will work as well.

这篇关于搜索和替换 --.sub(replacement, string[, count=0])- 不适用于特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆