Ruler Of The World Ruler Of The World - 1 month ago 11
Python Question

Printing in colour from an already defined variable

I currently have the code:

import sys

shell = sys.stdout.shell

my_name = ("Bob", "STRING")
friends_name = ("Jeff", "KEYWORD")
question = ("My name is %s in green and my friend's name is %s in red" % (my_name, friends_name))
shell.write(question)


I am trying to achieve an output of:

My name is Bob in green and my friend's name is Jeff in red.


And in the output the word
Bob
is green and
Jeff
is red.

However the code I tried simply gives an output of:

My name is ('Bob', 'STRING') in green and my friend's name is ('Jeff', 'KEYWORD') in red


I do know that just typing
shell.write("Bob", "STRING")
works but that takes up too many lines of code if you need to print more things in colour.

I have also tried to do

my_name = shell.write("Bob", "STRING")


But when you print that it just outputs
3


I need an answer of how to achieve the output, and also why it outputs
3
when printing

my_name = shell.write("Bob", "STRING")


I would also like to know why it strangely also prints 'Bobby' in green upon being defined like above

PS. I am on a Windows machine with python 3.4.3

Answer

Here's a way to do it:

import sys

def shell_print(txt, *args):

    out = txt.split("%s")
    # vars = [*args]     # See comments
    vars = list(args)
    for t in out:
        sys.stdout.shell.write(t)
        if vars:
            v = vars.pop(0)
            sys.stdout.shell.write(*v)

my_name = ("Bob", "STRING")
friends_name = ("Jeff", "KEYWORD")
question = "My name is %s in green and my friend's name is %s in red" 

shell_print(question, my_name, friends_name)

It's only a QAD (Quick and Dirty) solution, and will only for with "%s", but its a start. So the first parameter is the string containing the %s place holders, the following parameters (any number of them) are the variables, with their attributes, to be inserted.