Python 转义序列 \N{name} 不按定义工作 [英] Python escape sequence \N{name} not working as per definition
问题描述
我正在尝试按照其名称打印 unicode 字符,如下所示:
# -*- 编码:utf-8 -*-打印\N{SOLIDUS}"打印 "\N{BLACK SPADE SUIT}"
然而我得到的输出并不是很令人鼓舞.
转义序列按原样打印.
ActivePython 2.7.2.5 (ActiveState Software Inc.) 基于Python 2.7.2(默认,2011 年 6 月 24 日,12:21:10)[MSC v.1500 32 位(英特尔)] on输入帮助"、版权"、信用"或许可"以获取更多信息.>>># -*- 编码:utf-8 -*-...打印\N{SOLIDUS}"\N{固体}>>>打印 "\N{BLACK SPADE SUIT}"\N{黑桃套装}>>>
但是我可以看到 另一位提问者 已经能够成功地做到这一点.
怎么了?
那些序列只适用于unicode 字符串,这是 Python 3 中唯一的一种字符串.因此,在 Python 2 中,您需要在字符串文字前加上 u
.
文档中的相关行:
<块引用>\N{name}
Unicode 数据库中名为 name 的字符(仅限 Unicode)
I am trying to print unicode characters given their name as follows:
# -*- 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?
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
.
>>> 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)
这篇关于Python 转义序列 \N{name} 不按定义工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!