简体   繁体   中英

Color the integer output in color python

I have the bellow script which works fine, I only want to make The running sum is: integer output to be colored.

I have defined the class style which i am trying to use.

Code:

# cat calc_running_sum.py
#!/usr/local/bin/python3.6
import os    
os.system("")

# Group of Different functions for different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'
    
def running_sum(n):
    running_sum = 0
    for k in range(n):
        running_sum += k
    print(f'{"The running sum is: "} { running_sum }')
    # print( stlye.RED + f'{"The running sum is: "} { running_sum }')  < - this makes entire output RED

if __name__ == "__main__":
    running_sum(int(input("Enter an integer: ")))

Script Output:

# ./calc_running_sum.py
Enter an integer: 15
The running sum is:  105

In the above script 105 is the output which i want to printed in red color.

You can add codes in different places in string

print(f'The running sum is: {style.RED}{ running_sum }{style.RESET}')

The same without f-string

print('The running sum is:', style.RED, running_sum, style.RESET)

The same with format()

print('The running sum is: {}{}{}'.format(style.RED, running_sum, style.RESET))

You can use different colors in the same string - ie. green text and red sum

print(f'{style.GREEN}The running sum is: {style.RED}{ running_sum }{style.RESET}')

If you don't use {style.RESET} then text in all next print() will be also red

print(f'The running sum is: {style.RED}{ running_sum }')
print('This text is still red')
print('And this text is also red')

You can use use it also in input()

Red text and normal value entered by user

input(f"{style.RED}Enter an integer:{style.RESET} ")

Red text and green value entered by user

input(f"{style.RED}Enter an integer:{style.GREEN} ")

But after that you may have to print style.RESET (without '\n') to get again normal color in next strings.

input(f"{style.RED}Enter an integer:{style.GREEN} ")
print(style.RESET, end="") 

You can also assign color to variable to display wrong value on red and good value on green

if n >= 0:
    color = style.GREEN 
else:
    color = style.RED

print(f"Value: {color}{n}{style.RESET}")
#print("Value: {}{}{}".format(color, n, style.RESET))

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