簡體   English   中英

為 integer output 上色 python

[英]Color the integer output in color python

我有下面的腳本可以正常工作,我只想制作The running sum is: integer output 要着色。

我已經定義了我正在嘗試使用的 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: ")))

腳本 Output:

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

在上面的腳本105中是 output 我想用紅色打印。

您可以在字符串的不同位置添加代碼

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

沒有f-string也一樣

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

format()相同

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

您可以在同一字符串中使用不同的 colors - 即。 綠色文本和紅色總和

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

如果你不使用{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')

您也可以在input()中使用它

用戶輸入的紅色文本和正常值

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

用戶輸入的紅色文本和綠色值

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

但在那之后,您可能必須打印style.RESET (不帶 '\n')才能在下一個字符串中再次獲得正常顏色。

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

您還可以為變量分配顏色以在紅色上顯示錯誤值,在綠色上顯示良好值

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM