Ask Your Question
0

Is it possible to color a string in a list ?

asked 2024-03-15 10:20:50 +0200

Cyrille gravatar image

is there a way to color a string inside a list say

L = ["1","2","3"]

and I want to display 2 in red

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2024-03-15 14:50:48 +0200

rburing gravatar image

updated 2024-03-15 18:32:37 +0200

If you're using an interface that supports LaTeX output, such as a Jupyter notebook:

sage: show(["1", LatexExpr(r"{\color{red} 2}"), "3"])

$$\displaystyle \left[1, {\color{red} 2}, 3\right]$$

To automate it, you could do e.g.

sage: show([LatexExpr(r"{\color{red} " + latex(x) + "}") if x == "2" else x for x in L])

or

sage: show([LatexExpr(r"{\color{red} " + latex(x) + "}") if k == 1 else x for k, x in enumerate(L)])
edit flag offensive delete link more

Comments

I have tried to adapt your solution to a list of list but I certainly make an error M=[[1, 0],[0,1]] show([[LatexExpr(r"{\color{red} " + x + "}") if k == 1 else x for k, x in enumerate(M[i])]for i in range(len(M))])

Cyrille gravatar imageCyrille ( 2024-03-15 16:46:43 +0200 )edit

I've updated the answer: use latex(x) in the string concatenation.

rburing gravatar imagerburing ( 2024-03-15 18:34:39 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2024-03-15 10:20:50 +0200

Seen: 152 times

Last updated: Mar 15