python - 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 并打印结果时它没有注册 - 该字符仍然存在于字符串中。
解决方案
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
推荐阅读
- php - PHP 中的大量数字并不是它们看起来的那样
- actions-on-google - 德语 Google Assistant SSML 输出中的不需要的背景噪音
- opennms - 无法编译基本 MIB IE RFC 1407
- c++ - 将结构从 C++ 调用到 C
- pyspark - 生成两列之间的所有可能组合和一个指示符以显示该组合是否存在于源表中
- ios - 带有 TokBox 的 CallKit 在接听电话后检测到扬声器开启
- php - 传递变量laravel问题时未定义的变量
- apache-kafka-streams - 新建 KTable 不返回任何内容
- java - 如何在 Antlr 4 中创建和解析 if 语句
- c++ - 从不同的 QThread 访问 QObject 方法的安全性