python - Unicode 搜索不起作用

标签 python regex python-2.7 python-unicode

考虑一下。

# -*- coding: utf-8 -*-
data = "cdbsb \xe2\x80\xa6 abc"
print data 
#prints cdbsb … abc
              ^
print re.findall(ur"[\u2026]", data )

为什么re找不到这个unicode字符?我已经查过

\xe2\x80\xa6 === … === U+2026

最佳答案

我的猜测是,问题是因为 data 是一个字节字符串。您可能将控制台编码为 utf-8 ,因此在打印字符串时,控制台将字符串转换为 utf-8 然后显示它(您可以检查一下在 sys.stdout.encoding )。因此,您将获得字符 - ...

但很可能 re 不会为您执行此解码。

如果将 data 转换为 utf-8 编码,则在使用 re.findall 时将获得所需的结果。示例-

>>> data = "cdbsb \xe2\x80\xa6 abc"
>>> print re.findall(ur"[\u2026]", data.decode('utf-8') )
[u'\u2026']

关于python - Unicode 搜索不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33031009/

相关文章:

python - 使用 PySpark 迭代 SQL.Row 列表

regex - 如何构建正则表达式来查找字符串

mysql - 使用 python 更新 mysql

java - 正则表达式中的 Unicode 脚本

regex - Xmlstarlet select String+number for update

python - 如何用 Python 编写自己的 OrderedDict 类?

python - 天体 WCS : "IOError: Header missing END card."

javascript - Selenium 无法通过 XPath 识别元素

python - 模拟 datetime.now();模拟对象不被识别为类

python - 属性错误 : 'DataFrame' object has no attribute 'map'