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

时间:2023-01-04 20:34:26

I am trying to print unicode characters given their name as follows:

我正尝试列印以下列名称命名的unicode字符:

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

However the output I get is not very encouraging.

然而,我得到的结果并不令人鼓舞。

The escape sequence is printed as is.

转义序列按原样打印。

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}
>>>

I can however see that another asker has been able to do this successfully.

然而,我可以看到,另一个询问者已经成功地做到了这一点。

What's wrong?

怎么了?

1 个解决方案

#1


14  

Those sequences only work in unicode strings, which is the only kind of string Python 3 has. So in Python 2 you need to prefix the string literal with a u.

这些序列只在unicode字符串中工作,这是Python 3中惟一的一种字符串。所以在python2里,你需要用u给字符串加上前缀。

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

Relevant line from the docs:

文件相关行:

\N{name} Character named name in the Unicode database (Unicode only)

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

#1


14  

Those sequences only work in unicode strings, which is the only kind of string Python 3 has. So in Python 2 you need to prefix the string literal with a u.

这些序列只在unicode字符串中工作,这是Python 3中惟一的一种字符串。所以在python2里,你需要用u给字符串加上前缀。

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

Relevant line from the docs:

文件相关行:

\N{name} Character named name in the Unicode database (Unicode only)

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