【问题标题】:re.sub doesn't work properly in python [closed]re.sub 在 python 中无法正常工作 [关闭]
【发布时间】:2016-07-30 08:04:42
【问题描述】:

我的问题听起来很愚蠢,但有什么东西不适用于 python 3.x 和 re.sub?因为这个简单的代码似乎是错误的,所以它不会在我的控制台上打印 '(026) 660 68 21'。有人可以帮我吗?

import re    
word = "Tél : (026) 660 68 21"
w = re.sub("Tél : ", "", word, count=1)
print(w)

【问题讨论】:

  • 在我的控制台上工作。 Python 3.4.3,优麒麟。
  • 尝试在非 Unicode 字符上进行测试,例如re.sub("6", "", word, count=1) 带给你什么?
  • 你为什么首先使用 re.sub? w = word.replace("Tél : ", ""))。此外,如果 sub 不起作用,您很可能遇到编码问题
  • 现在打印什么?
  • 也适用于我的终端 3.4.1 OS X Yosemite。

标签: python regex python-3.x unicode


【解决方案1】:

我无法用您问题中的代码重现问题。

但是您所看到的可能会发生,例如,如果 e aigu 字符采用不同的形式:

>>> word = "Tél : (026) 660 68 21"
>>> substring = "Tél : "
>>> re.sub(substring, "", word, count=1)
'Tél : (026) 660 68 21'

修复:

>>> from unicodedata import normalize
>>> def n(str_, form='NFC'):
        return normalize(form, str_)
... 
>>> re.sub(n(substring), "", n(word), count=1)
'(026) 660 68 21'

【讨论】:

  • 也有可能,其中一个空格可能不是 U+0020,而是 these 中的任何一个(通常是 U+00A0)。如果有人恶作剧,冒号是this。
  • 我也在考虑e aigu,因为字符串是通过数据报废生成的,所以可能是问题所在。但是您的代码对我不起作用..但是感谢您的直觉,我要检查一下这一面
猜你喜欢
  • 1970-01-01
  • 2014-06-13
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
相关资源
最近更新 更多