String subscript given as integer

I’d like to write a function f(n::Int)::String such that f(1) = "x₁", f(2) = "x₂" and so on (assume 1<=n<=9 for simplicity). Since

julia> 'x' * '\u2081'
"x₁"

Let n=3; the syntax 'x' * '\u' * string(n + 2080) is invalid: ERROR: syntax: invalid escape sequence. The backslash can be escaped with “raw”, but how can i get the subscript back?

julia> 'x' * raw"\u" * "$(n + 2080)"
"x\\u2083"

This works

julia> foo(i) = "x" * Char(0x2080 + i)
foo (generic function with 1 method)

julia> foo(1)
"x₁"

julia> foo(2)
"x₂"

julia> foo(3)
"x₃"
3 Likes

Great, thanks!

Do you also have a solution for values greater than 9? i.e.:

julia> foo(12)
"x₁₂"
subscript(i) = join(Char(0x2080 + d) for d in reverse!(digits(i)))

Thanks! I thought about that. However, I do not like the small spaces between the digits in the subscript.

julia> "x"*subscript(123)
"x₁₂₃"

Is there any way to get rid of it? Except for using the LaTeXStrings?

Don’t use a monospaced font or use a text-rendering engine? Julia has no control over text-rendering of Unicode strings in a terminal.

Except for using the LaTeXStrings?

LaTeXStrings doesn’t actually do any text rendering either. It relys on you having an environtment (e.g. Jupyter) that supports LaTeX rendering. (In Jupyter, you could also use HTML subscripts with e.g. Docs.HTML("<sub>123</sub>")).)

1 Like