Convert any colour to the ANSI format to write in colours in your terminal.
Run this command to install ansiconverter
latest version:
python -m pip install -U ansiconverter
To install for development:
git clone https://github.com/thomassamoth/ansiconverter.git
cd ansiconverter
pip install -e .[dev]
To ensure the installation of this package has been successful, you can run the tests.
- Make sure you have installed the
pytest
module. Otherwise, run:
pip install pytest
- After you have downloaded the code and installed the package, run the tests by executing:
python -m pytest test/
⚠️ Warning
Some colour combinations between background and foreground are incompatible. The result can be slightly different from what is expected.
Convert from RGB colour to ANSI
# How to print a green text on a white background
from ansiconverter import RGBtoANSI
print(RGBtoANSI(text='Green text on a white background',foreground=(0, 255, 0), background=(255, 255, 255)))
Convert from hexadecimal to ANSI
# How to print a yellow text on a navy blue background, with hexadecimal values.
from ansiconverter import HEXtoANSI
print(HEXtoANSI('Some yellow text on blue background','#fdf31f', '000080'))
Convert from hexadecimal to RGB
from ansiconverter import HEXtoRGB
print(HEXtoRGB("#0b38c1"))
Result :
(11, 59, 193)
Convert from RGB to hexadecimal
from ansiconverter import RGBtoHEX
print(RGBtoHEX((11, 59, 193)))
Result :
"#0b3bc1"
ℹ️ Note
Another little tool has been added to convert RGB to hexadecimal and vice versa. It can't be used to write in colour in the terminal but could be useful for other applications.
Several text styles are available as well. You can even combine them with colours.
Style | Method |
---|---|
bold | bold |
italic | italic |
fainted | faint |
underlined | underline |
bold & underlined | bold_and_underline |
strikethroughed | strikethrough |
reversed (colours inverted) | reverse |
from ansiconverter import bold
print(bold("Some text in bold"))
Replace bold()
in the example with any method above to get the desired style.
It's also possible to combine text styles with colours:
from ansiconverter import HEXtoANSI, bold
print(bold(HEXtoANSI('A yellow text in bold','#f6cf6c')))
N.B: the order between the style and the text format isn't important and you can switch them, e.g.:
print(bold(HEXtoANSI('A yellow text in bold','#f6cf6c')))
will work the same as
print(HEXtoANSI(bold('A yellow text in bold'),'#f6cf6c'))
The structure of this repository is based on a talk by Mark Smith, which is available here, and the repo linked with the video.
This repository is licensed under the MIT license. See the LICENSE file for more information.