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)
来源:https://stackoverflow.com/questions/16076775/python-escape-sequence-nname-not-working-as-per-definition