0

I know that I can print the following:

print u'\u2550'

How do I do that with the .format string method? For example:

for i in range(0x2550, 0x257F):
    s = u'\u{04X}'.format(i) # of course this is a syntax error

1 Answer 1

1

You are looking for the unichr() function:

s = u'{}'.format(unichr(i))

or just plain

s = unichr(i)

unichr(integer) produces a unicode character for the given codepoint.

The \uxxxx syntax only works for string literals; these are processed by the Python compiler before running the code.

Demo:

>>> for i in range(0x2550, 0x257F):
...     print unichr(i)
... 
═
║
╒
╓
╔
╕
╖
# etc.

If you ever do have literal \uxxxx sequences in your strings, you can still have Python turn those into Unicode characters with the unicode_escape codec:

>>> print u'\\u2550'
\u2550
>>> print u'\\u2550'.decode('unicode_escape')
═
>>> print '\\u2550'.decode('unicode_escape')
═
>>> '\\u2550'.decode('unicode_escape')
u'\u2550'

In Python 2, you can use this codec on both byte string and unicode string values; the output is always a unicode string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.