Change the color of a single print line in Python 3.2?

I am working on a small text adventure in Python 3.2 when I learn it in order to practice and become more familiar with the language. In any case, I want to make sure that when certain actions are performed, the color of the print text changes. How to do it.

For example, the first text I want to do this for is:

if 'strength' in uniqueskill.lower(): time.sleep(3) print('As you are a Warrior, I shall supply you with the most basic tools every Warrior needs.') time.sleep(3) print('A sword and shield.') time.sleep(1) print('You have gained A SWORD AND SHIELD!') 
+4
source share
2 answers

Colorama is an excellent fully cross platform platform module for printing in a terminal / command line in different colors.

Example:

 import colorama from colorama import Fore, Back, Style colorama.init() text = "The quick brown fox jumps over the lazy dog" print(Fore.RED + text) print(Back.GREEN + text + Style.RESET_ALL) print(text) 

Gives you:

enter image description here

+26
source

You did not specify your platform, which is very important here, since most methods for outputting colored text to the console are platform specific. For example, the curses library that ships with Python is UNIX only, and ANSI codes no longer work with newer versions of Windows. The most cross-platform solution I can think of is to install and use a version of Windows curses on Windows computers.

Here is an example of using color with curses:

 import curses # initialize curses stdscr = curses.initscr() curses.start_color() # initialize color #1 to Blue with Cyan background curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_CYAN) stdscr.addstr('A sword and a shield.', curses.color_pair(1)) stdscr.refresh() # finalize curses curses.endwin() 

Note that curses are more complex than just colors. You can use it to define multiple windows on the console screen, position text using absolute or relative coordinates, manipulate keyboard inputs, etc. You can find the tutorial here: http://docs.python.org/dev/howto/curses.html

+6
source

All Articles