[英]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.我有下面的脚本可以正常工作,我只想制作
The running sum is:
integer output 要着色。
I have defined the class style
which i am trying to use.我已经定义了我正在尝试使用的 class
style
。
# 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: ")))
# ./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.在上面的脚本
105
中是 output 我想用红色打印。
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
没有
f-string
也一样
print('The running sum is:', style.RED, running_sum, style.RESET)
The same with format()
与
format()
相同
print('The running sum is: {}{}{}'.format(style.RED, running_sum, style.RESET))
You can use different colors in the same string - ie.您可以在同一字符串中使用不同的 colors - 即。 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如果你不使用
{style.RESET}
那么所有 next print()
中的文本也将是红色的
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()
您也可以在
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.但在那之后,您可能必须打印
style.RESET
(不带 '\n')才能在下一个字符串中再次获得正常颜色。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.