I am currently using python 2.7, and I am having a little bit of trouble coding this idea I have. I know it is easy enough to color text in the terminal in python 2.7 with libraries like colorama or termcolor, but these methods don't quite work in the way I am trying to use.
You see, I am trying to create a text based adventure game, that not only has colored text, but also gives a quick typewriter-style effect when doing so. I have the typewriter effect down pat, but anytime I try to integrate it with a colorizing library the code fails, giving me the raw ASCII character instead of the actual color.
import sys
from time import sleep
from colorama import init, Fore
init()
def tprint(words):
for char in words:
sleep(0.015)
sys.stdout.write(char)
sys.stdout.flush()
tprint(Fore.RED = "This is just a color test.")
If you run the code, you will see that the typewriter effect works, but the color effect does not. Is there any way I can "embed" the color into the text so that sys.stdout.write will show the color with it?
Thank You
EDIT
I think I may have found a workaround, but it is kind of a pain to change the color of individual words with this method. Apparently, if you use colorama to set the ASCII color before you call the tprint function, it will print in whatever the last set color was.
Here is the example code:
print(Fore.RED)
tprint("This is some example Text.")
I would love any feedback/improvements on my code, as I would really like to find a way to call the Fore library within the tprint function without causing ASCII errors.
TL;DR: Prepend your string with the desired
Fore.COLOURand don't forget toFore.RESETat the end.First of all - cool typewriter function!
In your workaround you are merely printing nothing (i.e. '') in red, then by default the next text you print is also in red. All text that follows will be in red until you
Fore.RESETthe colour (or exit).A better (more pythonic?) way is to directly and explicitly build your strings with the colour you want.
Here's a similar example, pre-pending
Fore.REDand appendingFore.RESETto the string before sending to yourtprint()function:Setting aside your
tprint()function for simplicity's sake, this method of colour-typing also works for concatenation of strings:Going further - to build a single string with multiple colours:
This is my first answer on Stack so I don't have the reputation required to post images of my terminal window output.
The official colorama docs have more useful examples and explanations. Hope I haven't missed too much, good luck!