Print a sequence (unicode)-subscript in python

Viewed 94

I'm trying to create a string like...

mystring = "X\u2080 + X\u2081 + X\u2082 + X\u2083 + ..."
print(mystring)

Which should output 'X₀ + X₁ + X₂ + X₃ + ...'

However, I want to add them sequentially with a loop.

I have tried:

mystring = ""
for i in range(0,4):
   mystring += f"X\u208{str(i)} +"

But I get the error

(unicode error) 'unicodeescape' codec can't decode bytes in position 1-5
truncated \uXXXX escape

What is the correct way of adding print terms with unicode sequentially in a loop?

1 Answers

Unicode escape sequences must be completely specified and can't be combined with placeholders in an f-string literal.

To generate unicode characters programatically, you can use the chr function instead:

mystring = ' + '.join(f"X{chr(0x2080 + i)}" for i in range(4))

mystring becomes:

X₀ + X₁ + X₂ + X₃
Related