May Mohammed
May Mohammed

Reputation: 31

Different colors for outputs in Python

I have a question that is asking me to print different colors for different instances. For example, for instance #1 print in blue color and for instance #2 print green color.

Please find the code I did below:

#function to display the output
def displayCustomer(self):
    customer=""
    if customer==customer1:
        print("\033[94m" "First Name: ", self.getfirstname(), "\nLast Name: ", self.getlastname(), "\nGender: ", self.getgender(), "\nPhone Number: ", self.getphone_number(), "\nHome Address: ", self.getaddress())
    else:
        print('\033[92m' "First Name: ", self.getfirstname(), "\nLast Name: ", self.getlastname(), "\nGender: ",self.getgender(), "\nPhone Number: ", self.getphone_number(), "\nHome Address: ", self.getaddress())

It doe's seem to work properly.

Upvotes: 0

Views: 62

Answers (2)

wasif
wasif

Reputation: 15470

ANSI sequences will only work if you are in DOS based-windows or Windows 10 with VT100 emulation, and in OS X. So you should make a look at Termcolor module

Upvotes: 0

David
David

Reputation: 8298

You can use the termcolor library like the following:

from termcolor import colored

for i, x in enumerate(["test1", "test2"]):
    if i == 0:
        print(colored('hello {:}'.format(x), 'blue'))
    else:
        print(colored('hello {:}'.format(x), 'green'))

Upvotes: 1

Related Questions