How to print an unicode char from formated string ? With following example i have an error (python3):
python -c 'print(u"\u{}".format("2665"))'
File "<string>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
It's kind of awkward, but you can use a raw string literal, encode, and then decode back using the unicode_escape
encoding:
print(r"\u{}".format("2665").encode().decode('unicode_escape'))
# ♥
"\\u{}\u0026quot;
throws that error because the string representation \\u \u003cem>nnnn
is not supposed to work with variables; it's a literal, immediate value . Much like you cannot do x = 't'; print ('a\\{}b'.format(x))
x = 't'; print ('a\\{}b'.format(x))
and expect a tab between a
and b
.
To print any Unicode character, either enter its literal code immediately into the string itself:
print ('Hello \u2665 world')
result:
Hello ♥ world
– do note that you don't need the u
prefix on the string itself; that's a Python 2.x'ism –, or, if you want to provide the character value in a variable:
print ('Hello {:c} world'.format(0x2665))
where (1) the :c
forces a character representation of the value, and (2) you need to indicate that the value itself is in hex. (As the string representation \\u \u003cem>nnnn
is always in hex.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.