Is there a way to generate a unicode by putting a '\' in front of a string with python?

Viewed 1945

Here is a normal way to print a unicode.

print('\u2080')

which outputs a subscripts character

₀

string format gives some material

for i in range(3):
    print('u208{}'.format(i))

outputs

u2080
u2081
u2082

I am trying to generate a unicode by putting a '\' in front of these.

I think I am almost there.

print('\\'+'u2080')

outputs

\u2080

How do I do next, to have this output the subscripts ₀ ?

2 Answers

You can use ord to transform the unicode character into an integer, apply your transformation (bitwise operators might be handy here depending on what you're doing), and then chr to convert back to the unicode character:

>>> print(list(chr(ord('\u2080') | i) for i in range(10)))
['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉']

You can also skip the ord and go strait from int to character:

>>> print(list(chr(0x2080 + i) for i in range(10)))
['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉']

Actually, working only with strings, without resorting to extracting the number of the codepoint and using the chr function, it is possible to create the correspondent unicode characters:

The module codecs in the stdlib have functions to register and get text codecs: the mappings from and to text to bytes, and some other text or byte transforms.

Among those transforms there is the unicode_escape character. It can be used directly when converting a bytes object to text using the bytes.decode method, but it also can be retrieved using codecs.getdecoder("unicode_escape") and convert text to text.

Therefore it is possible to do:

In [139]: import codecs                                                                                                                                

In [140]: esc = codecs.getdecoder("unicode_escape")                                                                                                    

In [141]: for i in range(10): 
     ...:     print(esc(f"\\u208{i}")[0], end=" ") 
     ...:      
     ...:      
     ...:                                                                                                                                              
₀ ₁ ₂ ₃ ₄ ₅ ₆ ₇ ₈ ₉ 

The call to the decoder returns a tuple with the result and the number of input characters consumed. The [0] after the call retrieves only the converted result.

(Above I used the "f-string" syntax that superseeded the .format method for almost all uses in Python 3.6)

Ordinarily one will prefer using the chr built-in, though - as it avoids juggling with string formatting and can deal with the numbers directly. (if we wanted more than 16 characters starting at a certain codepoint, the method above would not work as it is, for example).

print(" ".join(chr(0x2080 + i) for i in range(29)))

will print:

₀ ₁ ₂ ₃ ₄ ₅ ₆ ₇ ₈ ₉ ₊ ₋ ₌ ₍ ₎ ₏ ₐ ₑ ₒ ₓ ₔ ₕ ₖ ₗ ₘ ₙ ₚ ₛ ₜ

Related