Adding Style to Your Terminal Text
When working with command-line applications in Python, you might want to enhance the visual presentation of your output. While standard text printing displays characters directly, you can use ANSI escape codes to add styling such as bold, color, and underlines. This tutorial will guide you through the basics of using ANSI escape codes to format your terminal output.
What are ANSI Escape Codes?
ANSI escape codes are sequences of characters that instruct a terminal to perform specific actions, such as changing text color, setting text style, or moving the cursor. These codes start with an escape character (\033
) followed by a series of control codes.
Basic Styling: Bold Text
One common use case is making text bold. To achieve this, you can use the following ANSI escape code sequence:
\033[1m
– Starts bold formatting.\033[0m
– Resets formatting to default.
Here’s how you would use these codes in Python:
start_bold = "\033[1m"
end_bold = "\033[0m"
print(start_bold + "Hello, World!" + end_bold)
print("This is normal text.")
In this example, the text "Hello, World!" will be displayed in bold, while the subsequent line remains in the default style.
Combining Styles
You can combine multiple styles by chaining the corresponding escape codes. For instance, to create bold, underlined text, you could use:
\033[1m
– Bold\033[4m
– Underline\033[0m
– Reset
start_bold = "\033[1m"
start_underline = "\033[4m"
end_style = "\033[0m"
print(start_bold + start_underline + "Bold and Underlined!" + end_style)
Other Common Styles
Here are some other useful ANSI escape codes:
\033[30m
to\033[37m
: Set text color (black to white).\033[90m
to\033[97m
: Set bright text color (bright black to bright white).\033[7m
: Invert text color.
Considerations
- Terminal Support: ANSI escape codes are widely supported, but not all terminals interpret them correctly. The formatting might not be visible in some environments.
- Readability: Using escape codes directly in your code can make it less readable. It’s recommended to define constants or functions to encapsulate the formatting logic, as shown in the examples above.
- Alternative Libraries: While direct use of ANSI escape codes is possible, libraries like
termcolor
orcolorama
can simplify styling and provide cross-platform compatibility. These libraries abstract away the complexities of ANSI codes. They allow you to define styles in a more Pythonic way.
By leveraging ANSI escape codes, you can significantly enhance the visual appeal and clarity of your command-line applications.