如何让python接受unicode字符0x2000(及其他)

2024-10-01 13:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从Python中的字符串中删除某些字符。我有一个需要删除的字符列表或字符范围,用十六进制表示如下:

- "0x00:0x20"
- "0x7F:0xA0"
- "0x1680"
- "0x180E"
- "0x2000:0x200A"

我将此列表转换为如下所示的正则表达式:

re.sub(u'[\x00-\x20 \x7F-\xA0 \x1680 \x180E \x2000-\x200A]', ' ', my_str)

然而,当我有\x2000-\x200A时,我得到了一个错误。你知道吗

我发现Python实际上并没有将u'\x2000'解释为字符:

>>> '\x2000'
' 00'

它把它当作“x20”(一个空格)以及它后面的任何东西:

>>> '\x20blah'
' blah'

x2000是有效的unicode字符: http://www.unicodemap.org/details/0x2000/index.html

我希望Python以这种方式处理它,这样我就可以使用re将它从字符串中删除。你知道吗

另外,我想知道从字符串中删除这些字符的另一种方法。你知道吗

谢谢你的帮助。谢谢!你知道吗


Tags: 字符串re列表my错误字符xa0x00
2条回答

从文档(https://docs.python.org/2/howto/unicode.html):

Unicode literals can also use the same escape sequences as 8-bit strings, including \x, but \x only takes two hex digits so it can’t express an arbitrary code point. Octal escapes can go up to U+01ff, which is octal 777.

>>> s = u"a\xac\u1234\u20ac\U00008000"
... #      ^^^^ two-digit hex escape
... #          ^^^^^^ four-digit Unicode escape
... #                      ^^^^^^^^^^ eight-digit Unicode escape
>>> for c in s:  print ord(c),
...
97 172 4660 8364 32768

在unicode字符串中,需要指定unicode字符(\uNNNN而不是\xNNNN)。以下工作:

>>> import re
>>> my_str=u'\u2000abc'
>>> re.sub(u'[\x00-\x20 \x7F-\xA0 \u1680 \u180E \u2000-\u200A]', ' ', my_str)
' abc'

相关问题 更多 >