Pythonでカラー付きの文字を出力する方法

Pythonでは、サードパーティのライブラリcoloramaを使用してコマンドラインに色付きのフォントを出力できます。 coloramaライブラリはpipコマンドでインストールできます。

pip install colorama

インストール後、次のサンプルコードを使用して色つきのフォントを出力できます。

from colorama import init, Fore, Back, Style

# 初始化colorama
init()

# 输出红色的文字
print(Fore.RED + 'This text is red')

# 输出绿色的背景色和黄色的文字
print(Back.GREEN + Fore.YELLOW + 'This text has a green background and yellow text')

# 重置样式
print(Style.RESET_ALL + 'This text has the default style')

こうすることで、コマンドラインで色付きの文字列を出力できるようになります。注意:Windows 版では、colorama ライブラリを初期化するために init() メソッドを明示的に呼び出す必要があります。

bannerAds