How do I add colour to text in python?

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To add color to text in Python, you can use ANSI escape sequences. These escape sequences allow you to change the text color, background color, and other text formatting options in a terminal.

Here's an example of how you can add color to text using ANSI escape sequences in Python:

python
# Text color
print("\033[31mThis is red text\033[0m") # Red text
print("\033[32mThis is green text\033[0m") # Green text
print("\033[33mThis is yellow text\033[0m") # Yellow text

# Background color
print("\033[41mThis has a red background\033[0m") # Red background
print("\033[42mThis has a green background\033[0m") # Green background
print("\033[43mThis has a yellow background\033[0m") # Yellow background

# Combined color and background
print("\033[31;42mRed text with a green background\033[0m") # Red text with a green background

In the example above, \033[ starts the escape sequence, and m indicates the end of the sequence. The numbers between \033[ and m represent different ANSI escape codes for various text formatting options.

Here are some commonly used ANSI escape codes for text colors:

  • Red: \033[31m
  • Green: \033[32m
  • Yellow: \033[33m
  • Blue: \033[34m
  • Magenta: \033[35m
  • Cyan: \033[36m
  • White: \033[37m

Similarly, you can use ANSI escape codes for background colors by replacing the 3 with 4, like \033[41m for a red background.

To reset the text color and background to the default, use \033[0m.

Keep in mind that ANSI escape sequences may not work in all environments or terminals. They are primarily supported in Unix-like systems (e.g., Linux, macOS) and some Windows terminal emulators like PowerShell.