2

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 Answer 1

1

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₃
Sign up to request clarification or add additional context in comments.

2 Comments

I just realized that 0x2080 + i is only valid for values range(0,10). Do you know how I could make subscript 10, 11, 12, ...?
There are no unicode subscript numerals beyond 9, so you would have to switch your approach to, for example, certain formatting languages such as HTML, LaTeX, MathML, etc.

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.