Ever looked at your Python script’s output and thought, “Meh, it could be brighter… more alive?” Well, get ready to ditch the drab and embrace the fab with ANSI escape codes! These aren’t some arcane magic spells, but rather special sequences of characters that your terminal understands as instructions to change text color, style, and even cursor position. And the best part? Python’s print() function plays along beautifully!
The magic is performed by ANSI escape codes, and to make the matter simple, you just print them along with the rest of the text.
If you prefer to use a library instead, look at this article.
The basic structure of an ANSI escape code looks something like this: \033[…m.
- \033: This is the “escape” character, telling your terminal, “Hey, listen up! Something special is coming.”
- [: This marks the beginning of a control sequence.
- …: This is where you put your specific style codes (e.g., 31 for red text, 1 for bold).
- m: This signifies the end of the control sequence.
Let’s Get Colorful!
Ready to see it in action? Here are some common codes to get you started:
Text Colors:
- \033[30m: Black
- \033[31m: Red
- \033[32m: Green
- \033[33m: Yellow
- \033[34m: Blue
- \033[35m: Magenta
- \033[36m: Cyan
- \033[37m: White
Background Colors:
- \033[40m: Black background
- \033[41m: Red background
- …and so on, up to \033[47m for white background.
Text Styles:
- \033[1m: Bold
- \033[3m: Italic (though not all terminals support this)
- \033[4m: Underline
- \033[0m: Reset (super important! This clears all previous styling)
Putting It All Together: Examples!
Let’s sprinkle some magic on your print() statements:
# A simple red message
print("\033[31mThis text is red!\033[0m")
# Green and bold!
print("\033[1;32mSuccess! This is bold and green.\033[0m")
# Yellow text on a blue background
print("\033[44;33mWarning: Proceed with caution!\033[0m")
# Combining multiple styles
print("\033[1;4;35mMagenta, bold, and underlined!\033[0m")
# Remember to reset!
print("\033[31mThis is red.")
print("This text will also be red if you don't reset!\033[0m")
print("Now back to normal.")
