It’s important to understand here that the colouring done here is completely out of Python’s hands. When you run the Python interpreter in a terminal window, the terminal itself is a separate program, and that is the program that is actually interpreting these special characters as commands to change the colour.
The codes for specific colours are part of a standard called ANSI. You can research this easily with a search engine, but adding these special colour-formatting sequences to strings is tedious and error-prone. It’s better to use a third-party library for this task. @rob42 already showed you termcolor
. Another library worth mentioning is colorama
; it doesn’t solve quite the same problems, though.
In an interpreter session, writing something like res
will cause the interpreter to echo back a string representation of whatever object res
is, using the built-in repr
to create that representation. This version will put quotes around strings and use escape sequences for special characters, because its purpose is to show you what an object actually is, not to display text. Using str
will not help, because the interpreter will still take the repr
of that str
. (In fact, using str
here will do nothing, because res
is already a string.)
This cannot really be done, because the colour is not a property of the string, list, or any other Python object. It is a result of work done by another program, when you give it special text. However, with a bit of work, you can make objects that are naturally displayed in a specific color. If your terminal supports ANSI.
You cannot change the text that will be used to represent a built-in string or list with repr
. However, you can create your own classes, and use the special __repr__
method to describe what will happen when repr
is used on the object. You can also inherit from the built-in str
and list
types. Thus, taking advantage of termcolor
:
>>> from termcolor import colored
>>> class RedList(list):
... def __repr__(self):
... return colored(super().__repr__(), 'red')
...
>>> RedList([1,2,3])
[1, 2, 3]
>>>
It isn’t shown here, but the RedList
instance should show up in red in the terminal.
Similarly,
>>> class GreenString(str):
... def __repr__(self):
... return colored(super().__repr__(), 'green')
...
>>> GreenString('test')
'test'
The string will show up in green - including the quotes, because they are part of the text that colored
is surrounding with ANSI color codes.