How can I print bold text in Python?
Asked Answered
C

17

274

E.g:

print "hello"

What should I do to make the text "hello" bold?

Chickenhearted answered 19/1, 2012 at 10:6 Comment(4)
duplicate of color text in terminal aplications in unix . Lots of links in the answers. That answer is in C, but easily translated to Python.Wellman
Which terminal are you using? Are you on Unix or Windows?Goatsbeard
i'm using safari. Just found out i can use HTML tags in python.Chickenhearted
Safari may imply Mac OS X v10.7 (Lion).Dasilva
G
631
class color:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

print(color.BOLD + 'Hello, World!' + color.END)
Guzel answered 25/6, 2013 at 17:10 Comment(4)
This no longer works with Python 3.9.Backbreaking
So what does work in 3.9+?Homeland
@Backbreaking this works in python 3.10.9Unreserve
The only thing in this answer that might depend on the Python version is the use of the print function rather than a print statement. The actual color stuff depends on your terminal recognizing the escape sequences, nothing to do with Python itself.Amparoampelopsis
S
108

Use this:

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

And to change back to normal:

print '\033[0m'

This page is a good reference for printing in colors and font-weights. Go to the section that says 'Set graphics mode:'

And note this won't work on all operating systems but you don't need any modules.

Subminiaturize answered 2/8, 2012 at 19:37 Comment(0)
B
53

You can use termcolor for this:

 sudo pip install termcolor

To print a colored bold:

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

For more information, see termcolor on PyPi.

simple-colors is another package with similar syntax:

 from simple_colors import *
 print(green('Hello', ['bold'])

The equivalent in colorama may be Style.BRIGHT.

Beekeeping answered 26/11, 2013 at 7:20 Comment(0)
S
34

You can rely on ANSI escape codes if your terminal supports them:

>>> start = "\033[1m"
>>> end = "\033[0;0m"
>>> print "The" + start + "text" + end + " is bold."
The text is bold.

The word text will be bold when printed.

Skyros answered 19/1, 2012 at 10:11 Comment(3)
Re "using Linux": Why is that? ANSI escape sequences? Can you elaborate in your answer? What are the preconditions for it to work (e.g., terminal emulation support)? - where doesn't it work? But ********* without ********* "Edit:", "Update:", or similar - the answer should appear as if it was written today)Dasilva
Whether or not the terminal understands the ANSI escape sequences used in the answer has nothing to do with the underlying operating system.Amparoampelopsis
I edited the answer. So many things I didn't know about ANSI escape codes and terminals in the past :-)Skyros
H
32

In straight-up computer programming, there is no such thing as "printing bold text". Let's back up a bit and understand that your text is a string of bytes and bytes are just bundles of bits. To the computer, here's your "hello" text, in binary.

0110100001100101011011000110110001101111

Each one or zero is a bit. Every eight bits is a byte. Every byte is, in a string like that in Python 2.x, one letter/number/punctuation item (called a character). So for example:

01101000 01100101 01101100 01101100 01101111
h        e        l        l        o

The computer translates those bits into letters, but in a traditional string (called an ASCII string), there is nothing to indicate bold text. In a Unicode string, which works a little differently, the computer can support international language characters, like Chinese ones, but again, there's nothing to say that some text is bold and some text is not. There's also no explicit font, text size, etc.

In the case of printing HTML, you're still outputting a string. But the computer program reading that string (a web browser) is programmed to interpret text like this is <b>bold</b> as "this is bold" when it converts your string of letters into pixels on the screen. If all text were WYSIWYG, the need for HTML itself would be mitigated -- you would just select text in your editor and bold it instead of typing out the HTML.

Other programs use different systems -- a lot of answers explained a completely different system for printing bold text on terminals. I'm glad you found out how to do what you want to do, but at some point, you'll want to understand how strings and memory work.

Howlet answered 19/1, 2012 at 17:44 Comment(0)
C
18

There is a very useful module for formatting text (bold, underline, colors, etc.) in Python. It uses the curses library, but it's very straightforward to use.

An example:

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')

I wrote a simple module named colors.py to make this a little more pythonic:

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")
Chessman answered 19/1, 2012 at 10:17 Comment(0)
H
16

Check out Colorama. It doesn't necessarily help with bolding... but you can do colorized output on both Windows and Linux, and control the brightness:

from colorama import *

init(autoreset=True)
print Fore.RED + 'some red text'
print Style.BRIGHT + Fore.RED + 'some bright red text'
Hannahhannan answered 19/1, 2012 at 12:21 Comment(0)
O
16
print '\033[1m  Your Name  \033[0m'

\033[1m is the escape code for bold in the terminal. \033[0m is the escape code for end the edited text and back default text format.

If you do not use \033[0m then all upcoming text of the terminal will become bold.

Obara answered 28/6, 2018 at 5:1 Comment(0)
C
10

Install the termcolor module

sudo pip install termcolor

and then try this for colored text

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

or this for bold text:

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

In Python 3 you can alternatively use cprint as a drop-in replacement for the built-in print, with the optional second parameter for colors or the attrs parameter for bold (and other attributes such as underline) in addition to the normal named print arguments such as file or end.

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

Full disclosure, this answer is heavily based on Olu Smith's answer and was intended as an edit, which would have reduced the noise on this page considerably but because of some reviewers' misguided concept of what an edit is supposed to be, I am now forced to make this a separate answer.

Carryingon answered 15/10, 2019 at 9:20 Comment(0)
F
5

A simple approach relies on Unicode Mathematical Alphanumeric Symbols.

Code

def bold(
    text,
    trans=str.maketrans(
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
        "𝗔𝗕𝗖𝗗𝗘𝗙𝗚𝗛𝗜𝗝𝗞𝗟𝗠𝗡𝗢𝗣𝗤𝗥𝗦𝗧𝗨𝗩𝗪𝗫𝗬𝗭𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇𝟬𝟭𝟮𝟯𝟰𝟱𝟲𝟳𝟴𝟵",
    ),
):
    return text.translate(trans)

Example

assert bold("Hello world") == "𝗛𝗲𝗹𝗹𝗼 𝘄𝗼𝗿𝗹𝗱"

Discussion

Several pros and cons I can think of. Feel free to add yours in the comments.

Advantages:

  • As short as readable.
  • No external library.
  • Portable: can be used for instance to highlight sections in an ipywidgets Dropdown.
  • Extensible to italics, etc. with the appropriate translation tables.
  • Language agnostic: the same technique can be implemented in any programming language.

Drawbacks:

  • Requires Unicode support and a font where all the required glyphs are defined. This should be ok on any reasonably modern system, though.
  • No copy-paste : produces a faux-text. Note that '𝘄𝗼𝗿𝗹𝗱'.isalpha() is still True, though.
  • No diacritics.

Implementation notes

  • In the code above, the translation table is given as an optional argument, meaning that it is evaluated only once, and conveniently encapsulated in the function which makes use of it. If you prefer a more standard style, define a global BOLD_TRANS constant, or use a closure or a lightweight class.
Fritzsche answered 25/3, 2022 at 10:17 Comment(0)
C
4

Simple boldness - two-line code

In Python 3, you could use Colorama - simple_colors: (On the Simple Colours page*, go to the heading 'Usage'.) Before you do what is below. Make sure you pip install simple_colours.

from simple_colors import *

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

Enter image description here

Cotterell answered 23/11, 2019 at 19:49 Comment(0)
D
3

Some terminals allow to print colored text. Some colors look like if they are "bold". Try:

print ('\033[1;37mciao!')

The sequence '\033[1;37m' makes some terminals to start printing in "bright white" that may look a bit like bolded white. '\033[0;0m' will turn it off.

Dogs answered 19/1, 2012 at 10:11 Comment(0)
D
3

Assuming that you really mean "print" on a real printing terminal:

>>> text = 'foo bar\r\noof\trab\r\n'
>>> ''.join(s if i & 1 else (s + '\b' * len(s)) * 2 + s
...         for i, s in enumerate(re.split(r'(\s+)', text)))
'foo\x08\x08\x08foo\x08\x08\x08foo bar\x08\x08\x08bar\x08\x08\x08bar\r\noof\x08\
x08\x08oof\x08\x08\x08oof\trab\x08\x08\x08rab\x08\x08\x08rab\r\n'

Just send that to your stdout.

Draught answered 19/1, 2012 at 10:53 Comment(0)
C
3

The bold text goes like this in Python:

print("This is how the {}bold{} text looks like in Python".format('\033[1m', '\033[0m'))

This is how the bold text looks like in Python.

Cholecystitis answered 26/9, 2022 at 12:16 Comment(1)
What are the presumptions? Using a VT100 terminal? What system was it tested on (Arch Linux?), in detail (like the shell), incl. versions? Please respond by editing (changing) your answer, not here in comments (************ without ************ (******** WITHOUT ********) "Edit:", "Update:", or similar - the answer should appear as if it was written today).Dasilva
G
1

There is something called escape sequence which is used to represent characters that is not available in your keyboard. It can be used for formatting text (in this case bold letter format), represent special character with specific ASCII code and to represent Unicode characters.

In Python, escape sequences are denoted by a backslash \ followed by one or more characters. For example, the escape sequence \n represents a newline character, and the escape sequence \t represents a tab character.

Here for formatting text in bold use \033[1m before and after the text you want to represent in bold.

example-

print("This line represent example of \033[1mescape sequence\033[0m.")

In the escape sequence \033[1m, the 1 enables bold text, while the m is the command to set the text formatting. The \033[0m escape sequence resets the text formatting to the default settings.

The \033[0m escape sequence is used after the \033[1m escape sequence to turn off bold text and return to the default text formatting. This is necessary because the \033[1m escape sequence only enables bold text, it does not disable it.

Gabo answered 5/1, 2023 at 21:34 Comment(0)
C
0

Printing in bold made easy.

Install quo using pip:

from quo import echo
echo(f"Hello, World!", bold=True)
Chadchadabe answered 9/8, 2021 at 7:26 Comment(0)
A
-1
def say(text: str):  
  print ("\033[1;37m" + text)

say("Hello, world!")

my code works okay.

Auerbach answered 19/1, 2023 at 16:40 Comment(1)
This leaves the text in bold because the end sequence isn't present. Paste your func into a python session in a terminal and then call it on a string. It will print it in bold, but the next line you type will still be bold. In order to get back to normal you need to run print("\033[0m"). That's because you never tell the interpreter to stop printing bold characters.Dorsoventral

© 2022 - 2024 — McMap. All rights reserved.