Python转义序列\ N {name}不能按照定义工作

时间:2013-04-18 07:18:24

标签: python unicode python-2.7 unicode-string python-unicode

我正在尝试打印unicode字符,其名称如下:

# -*- coding: utf-8 -*-
print "\N{SOLIDUS}"
print "\N{BLACK SPADE SUIT}"

然而,我得到的输出并不是很令人鼓舞。

转义序列按原样打印。

ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on
Type "help", "copyright", "credits" or "license" for more information.
>>> # -*- coding: utf-8 -*-
... print "\N{SOLIDUS}"
\N{SOLIDUS}
>>> print "\N{BLACK SPADE SUIT}"
\N{BLACK SPADE SUIT}
>>>

但我可以看到another asker已成功完成此操作。

怎么了?

1 个答案:

答案 0 :(得分:16)

Those sequences only work in unicode strings,这是Python 3中唯一的字符串。因此,在Python 2中,您需要在字符串文字前加u

>>> print "\N{SOLIDUS} \N{BLACK SPADE SUIT}"
\N{SOLIDUS} \N{BLACK SPADE SUIT}
>>> print u"\N{SOLIDUS} \N{BLACK SPADE SUIT}"
/ ♠

文档中的相关行:

  

\N{name} Unicode数据库中的字符名称(仅限Unicode)

相关问题