【问题标题】:Search and replace --.sub(replacement, string[, count=0])-does not work with special characters搜索和替换 --.sub(replacement, string[, count=0]) - 不适用于特殊字符
【发布时间】: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',否则反斜杠会给你带来无穷无尽的麻烦。

标签: python regex replace


【解决方案1】:

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

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

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

请注意,\n\t 也可以使用。

【讨论】:

  • 谢谢!但是,出于我无法理解的原因,您的代码将 \t 替换为 而不是 。
  • 如果您在交互模式下查看它,那么是的,您会看到加倍的反斜杠,因为它以与您相同的形式向您显示 representation在源代码中使用。但是如果你用print(s) 显示它,你会得到一个更易读(但更模糊)的模式。查找 str()repr()
猜你喜欢
  • 2011-04-23
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
相关资源
最近更新 更多