首页 > 解决方案 > python replace 和 sub 不适用于 unicode 字符 u"\u0092"

问题描述

Python 版本:Python 3.6。我正在尝试用常规撇号替换 Unicode 字符 u"\u0092" (又名卷曲撇号)。

我已经尝试了以下所有方法:

    mystring = <some string with problem character>
    # option 1 
    mystring = mystring.replace(u"\u0092", u\"0027")
    # option 2 
    mystring = mystring.replace(u"\u0092", "'")
    # option 3
    mystring = re.sub('\u0092',u"\u0027", mystring)
    # option 4
    mystring = re.sub('\u0092',u"'", mystring)

以上都没有更新 mystring 中的字符。其他子和替换操作正在工作 - 这让我认为这要么是我使用 Unicode 字符的问题,要么是这个特定字符的问题。

更新:我也尝试过以下建议,但都不起作用:

    mystring.decode("utf-8").replace(u"\u0092", u"\u0027").encode("utf-8")
    mystring.decode("utf-8").replace(u"\u2019", u"\u0027").encode("utf-8")

但它给了我错误: AttributeError: 'str' object has no attribute 'decode'

澄清一下:IDE 不是这里的核心问题。我的问题是为什么当我使用 Unicode 字符运行 replace 或 sub 并打印结果时它没有注册 - 该字符仍然存在于字符串中。

标签: pythonregexstringtext

解决方案


your code is wrong it's \u2019 for apostrophe (’). from wikipedia

U+0092 146 Private Use 2 PU2

that's why eclipse is not happy.


with the right code:

#_*_ coding: utf8 _*_
import re
string = u"dkfljglkdfjg’fgkljlf"
string = string.replace(u"’", u"'"))
string = string.replace(u"\u2019", u"\u0027")
string = re.sub(u'\u2019',u"\u0027", string)
string = re.sub(u'’',u"'", string)

all solutions work

and don't call your vars str


推荐阅读