Home >Backend Development >Python Tutorial >How Can I Print Colored Text to My Terminal Using Python?

How Can I Print Colored Text to My Terminal Using Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-28 13:13:11768browse

How Can I Print Colored Text to My Terminal Using Python?

Printing Colored Text to the Terminal in Python

To output colored text to the terminal in Python, you can use ANSI escape sequences. These sequences allow you to control the appearance of your text, including its color.

To use ANSI escape sequences, you'll need a class like this:

class bcolors:
    HEADER = '3[95m'
    OKBLUE = '3[94m'
    OKCYAN = '3[96m'
    OKGREEN = '3[92m'
    WARNING = '3[93m'
    FAIL = '3[91m'
    ENDC = '3[0m'
    BOLD = '3[1m'
    UNDERLINE = '3[4m'

To use this class, you can do something like this:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

Or, with Python 3.6 :

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on macOS, Linux, and Windows (with certain configurations). There are ANSI codes for setting the color, changing the font weight, moving the cursor, and more.

If you plan to extensively work with colors and formatting, consider using the "curses" module. It simplifies the process and provides a range of capabilities for text manipulation.

Alternatives for Non-Extended ASCII

If your system doesn't support extended ASCII, your options are limited to the ASCII characters below 127. "#" or "@" are possible choices for block characters.

If your terminal uses an IBM extended ASCII character set, you'll have more options. Characters like 176, 177, 178, and 219 are considered "block characters."

Advanced Techniques

Some modern text-based programs like "Dwarf Fortress" emulate text mode in a graphical environment. They use bitmaps of classic PC fonts to create more visually appealing text. You can find these bitmaps on the Dwarf Fortress Wiki.

Additionally, the Text Mode Demo Contest provides resources for creating graphics in text mode, which may be useful for advanced projects.

The above is the detailed content of How Can I Print Colored Text to My Terminal Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn