Home > Backend Development > Python Tutorial > How Can I Print Colored Text to the Terminal in Python?

How Can I Print Colored Text to the Terminal in Python?

Susan Sarandon
Release: 2024-12-29 16:24:12
Original
1007 people have browsed it

How Can I Print Colored Text to the Terminal in Python?

Printing Colored Text in Python

In Python, you can output colored text to the terminal using ANSI escape sequences. This works on Unix-based systems like Linux, macOS, and Windows with ANSICON installed or VT100 emulation enabled. Here's an example:

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'
Copy after login

To use this, you can write code like:

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

With Python 3.6 , you can also use f-strings:

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

Extended Considerations:

For more complex text formatting, consider using the "curses" module. It simplifies cursor movement and advanced text manipulation.

If you're working with limited ASCII characters, characters like '#' and '@' can be useful for blocks. On IBM extended ASCII character sets, characters 176-178 and 219 represent block characters.

Modern programs like "Dwarf Fortress" use graphical mode to emulate text mode, allowing for the use of bitmap fonts.

The Text Mode Demo Contest provides additional resources for creating graphics in text mode.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template