E.g:

print "hello"

我该怎么做才能将“hello”文本加粗?


当前回答

看看Colorama。它不一定对加粗有帮助……但是你可以在Windows和Linux上进行彩色输出,并控制亮度:

from colorama import *

init(autoreset=True)
print Fore.RED + 'some red text'
print Style.BRIGHT + Fore.RED + 'some bright red text'

其他回答

看看Colorama。它不一定对加粗有帮助……但是你可以在Windows和Linux上进行彩色输出,并控制亮度:

from colorama import *

init(autoreset=True)
print Fore.RED + 'some red text'
print Style.BRIGHT + Fore.RED + 'some bright red text'

用这个:

print '\033[1m' + 'Hello'

和变回正常:

print '\033[0m'

本页是打印颜色和字体粗细的很好的参考。转到“设置图形模式”部分:

注意,这并不适用于所有操作系统,但您不需要任何模块。

简单的粗体-两行代码

在Python 3中,你可以使用Colorama - simple_colors: (在简单颜色页面*,转到标题“用法”。)在你做下面的事情之前。确保你安装了simple_colors。

from simple_colors import *

print(green('hello', 'bold'))

安装termcolor模块

sudo pip install termcolor

然后对彩色文本试试这个

from termcolor import colored
print colored('Hello', 'green')

对于粗体文本:

from termcolor import colored
print colored('Hello', attrs=['bold'])

在Python 3中,除了常规的命名打印参数(如file或end)外,您还可以使用cprint作为内置打印的下拉替换,使用可选的第二个参数表示颜色或attrs参数表示粗体(以及其他属性,如下划线)。

import sys
from termcolor import cprint
cprint('Hello', 'green', attrs=['bold'], file=sys.stderr)

完全披露,这个答案很大程度上是基于奥卢·史密斯的答案 本来是想编辑一下,这样可以减少本页的噪音 相当多,但因为一些评论家的错误概念 编辑应该是什么样子,我现在不得不把这作为一个单独的答案。

Python中有一个非常有用的模块用于格式化文本(粗体、下划线、颜色等)。它使用curses库,但是使用起来非常简单。

一个例子:

from terminal import render
print render('%(BG_YELLOW)s%(RED)s%(BOLD)sHey this is a test%(NORMAL)s')
print render('%(BG_GREEN)s%(RED)s%(UNDERLINE)sAnother test%(NORMAL)s')

我写了一个名为colors.py的简单模块,让它更python化一些:

import colors

with colors.pretty_output(colors.BOLD, colors.FG_RED) as out:
    out.write("This is a bold red text")

with colors.pretty_output(colors.BG_GREEN) as out:
    out.write("This output have a green background but you " +
               colors.BOLD + colors.FG_RED + "can" + colors.END + " mix styles")