1

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.

agf
  • 171,228
  • 44
  • 289
  • 238
nsh
  • 1,499
  • 6
  • 13
  • 14

3 Answers3

3

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"
Suhail Patel
  • 13,644
  • 2
  • 44
  • 49
2

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

Community
  • 1
  • 1
Don Question
  • 11,227
  • 5
  • 36
  • 54
0
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/

Izaz
  • 85
  • 1
  • 2
  • 10
  • But this answer essentially reiterates what has already been said (not to mention the `os.system()` step seems rather arbitrary. – Ondrej K. Feb 25 '20 at 15:33