Reputation: 1529
I am aware of printing the statements in color. Eg:
"\033[34mHow are you ? \033[0m" -> This will print the statement in blue color.
But what if the string is stored in a variable, and then I need to print the value of the variable in color.
string= "How are you?"
print string
In the above case, I need when the value of string is printed, the output is in blue color.
Upvotes: 1
Views: 12796
Reputation: 85
import os
os.system("")
message='How are you?'
print('\033[0;32m'+message+'\033[0m')
Output:
How are you? (it will be print in green color)
For the color code reference please check: https://ozzmaker.com/add-colour-to-text-in-python/
Upvotes: 0
Reputation: 11614
You could use formated strings (old-style) like:
colors = {'reset':'\033[0m', 'blue':'\033[34m'}
person = 'you'
formattext = 'How are %s%s%s' %(colors['blue'], person, colors['reset'])
%s defines a string place-holder see: http://docs.python.org/library/stdtypes.html#string-formatting
btw: Stack overflow on python string formating
Upvotes: 2
Reputation: 13694
You could just concat the colour sections of the String together when printing your string like so:
string = "How are you?"
print "\033[34m" + string + "\033[0m"
Upvotes: 3