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

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

Susan Sarandon
Release: 2024-12-25 20:31:14
Original
185 people have browsed it

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

Outputting Colored Text to the Terminal in Python

In Python, printing colored text to the terminal can be achieved through ANSI escape sequences. For instance, consider the following Python code:

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 utilize these color codes, you can write code as follows:

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

Alternatively, with Python 3.6 , you can use f-strings:

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

This approach works for various operating systems, including OS X, Linux, and Windows (with ANSICON or VT100 emulation enabled). ANSI codes allow for controlling text color, cursor movement, and more.

For complex text manipulation, consider using the Python "curses" module, which simplifies advanced tasks related to color printing. Reference the Python Curses HowTO for guidance.

The above is the detailed content of How Can I Output 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