Terminal String Styling
Style is a simple and fast Python library for styling terminal output with colors and formatting using ANSI escape codes. It provides a clean API for foreground colors, background colors, and text effects. The current version is 1.1.6, and it maintains a stable, active release cadence.
Common errors
-
NameError: name 'fg' is not defined
cause Attempting to use `fg` (or `bg`, `ef`, `style`) without importing it from the `style` library.fixEnsure you import the necessary components: `from style import style, fg, bg, ef`. -
AttributeError: module 'style.fg' has no attribute 'RED'
cause You are trying to access a color or effect attribute using uppercase letters (e.g., `fg.RED`) instead of the correct lowercase form.fixChange the attribute name to its lowercase equivalent, for example, `fg.red`, `bg.blue`, or `ef.bold`. -
My terminal output is not colored or styled, just plain text or strange characters.
cause The terminal emulator you are using may not support ANSI escape codes, or the output is being redirected (e.g., to a file) which often disables styling. On older Windows versions, `colorama` (which `style` uses) might not be fully initialized or the terminal itself lacks sufficient support.fixEnsure you are using a modern terminal emulator (e.g., Windows Terminal, iTerm2, Alacritty, gnome-terminal). If on Windows, ensure `colorama` is installed (`pip install colorama`) as `style` relies on it for cross-platform compatibility. Avoid redirecting output to files if you expect styled text.
Warnings
- gotcha When applying styles using the `style()` function, inner `style()` calls effectively create new styled segments that are concatenated. This means that a parent style will not 'wrap' a child styled segment as it implicitly resets before and after each `style()` call.
- gotcha Styles (colors and effects) are applied by their lowercase attribute names (e.g., `fg.red`, `ef.bold`). Using uppercase attribute names (e.g., `fg.RED`) will result in an `AttributeError`.
Install
-
pip install style
Imports
- style, fg, bg, ef
from style import style, fg, bg, ef
Quickstart
from style import style, fg, bg, ef
print(style("Hello, World!", fg.red, bg.blue, ef.bold))
print(style("Underlined text.", ef.underline))
print(style("Green background.", bg.green))