bux
bux

Reputation: 7799

Print unicode from formated string

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

Upvotes: 3

Views: 261

Answers (2)

Jongware
Jongware

Reputation: 22478

"\u{}" throws that error because the string representation \unnnn 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)) 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 \unnnn is always in hex.)

Upvotes: 4

DeepSpace
DeepSpace

Reputation: 81684

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'))
#  ♥

Upvotes: 4

Related Questions