简体   繁体   中英

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.

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'))

ANSI 序列仅适用于基于 DOS 的 Windows 或带有 VT100 仿真的 Windows 10 和 OS X。所以你应该看看Termcolor 模块

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM