Kodeclik Blog
How to bold text in Python
When working with text in Python, you might want to emphasize certain words or phrases to make them stand out. One way to achieve this effect is by printing bold text. While Python doesn't have built-in support for formatting text in this way, you can use control characters or specialized libraries to accomplish the task. In this blog post, we'll explore how to print bold text in Python using these approaches.
Method 1: Use control characters
Control characters are special characters that don't have a visible representation but instead control various aspects of text formatting and display. In Python, you can use control characters, specifically ANSI escape codes, to change the style of your text. These codes are sequences of characters that, when printed to the terminal, modify the text's appearance.
Printing Bold Text in Python using ANSI escape sequences
To make text bold, we'll use the ANSI escape code for bold text, which is \033[1m. This code tells the terminal to switch to bold text mode. To turn off bold text, you can use the ANSI escape code \033[0m.
Let's start by printing a simple message in bold text using control characters:
print(“This text is not bold.”)
print("\\033[1mThis text is bold!\\033[0m")
In this example, we use \033[1m before the text we wish to make bold and \033[0m after it to reset the text style. The message (or string) that we would like to print is thus in between these control characters.
When you run this code, you'll see "This text is bold!" displayed in bold in your terminal, like so:
Adding Bold Text to Variables
You can also add bold text in the values we set to variables and include them in your output. Here's an example:
bold_text = "\\033[1mThis text is bold!\\033[0m"
print("Regular text and " + bold_text + " back to regular text.")
In this example, we create a variable bold_text that contains the bold text with the appropriate control characters. We then concatenate it with other text to create a more complex output.
Creating Functions for Bold Text
If you plan to use bold text frequently, it's a good idea to create a function to simplify the process. Here's a basic function that you can use:
def bold_text(text):
return "\\033[1m" + text + "\\033[0m"
print("Regular text and "
+ bold_text("this is bold")
+ " back to regular text.")
This function, bold_text(), takes a string as input and returns the string formatted in bold.
How to make bold alternate characters in a string
In order to alternate between setting characters in a string to bold, you can use control characters in a plain text document. Here is a Python program:
original_string = "Hello, World!"
formatted_string = ""
for index, char in enumerate(original_string):
if index % 2 == 0:
formatted_string += f'\\033[1m{char}\\033[0m'
else:
formatted_string += char
print(formatted_string)
In the above code, we iterate through the characters in the original_string using enumerate to keep track of the character's index. If the index is even (0-based index), we enclose the character in control characters (\033[1m for bold start and \033[0m for formatting end) to make it bold. If the index is odd, we simply add the character without any formatting. This will result in alternate characters in the string being displayed in bold, while the others remain in their regular format.
Thus, using control characters, specifically ANSI escape codes, is an easy way to print bold text in Python. This simple technique allows you to add emphasis to your output and improve the readability of your text-based applications.
Whether you're creating command-line tools or enhancing the user experience in your terminal, knowing how to print bold text using control characters is a valuable skill.
But note that this control character approach might not work in environments that don't support ANSI, like some text editors, logging systems, or certain Windows command prompts (unless ANSI support is enabled). For these cases, we have to explore other ways to bold characters, such as specialized Python libraries.
Method 2: Use the rich library
The rich library is a Python package designed to make it easy to render rich text and beautiful formatting in terminal applications. It allows you to not just add bold characters to your outputs but also colors, styles, and even complex layouts to console output. This significantly enhances the visual appeal of the output of your programs!
For this, you have to first install the "rich" library using a command like "pip install rich". After that, you can write programs like the following:
from rich.console import Console
# Create a console object for rich text output
console = Console()
# Display different styles of text
console.print("[bold]This is bold text using rich![/bold]")
console.print("[underline]This is underlined text using rich![/underline]")
console.print("[bold italic]This is bold and italic text using rich![/bold italic]")
console.print("[bold red]This is bold and red text using rich![/bold red]")
The output will be:
Method 3: Use the markdown library
In general, and especially as shown in the two methods above, we need to understand that there is no "bold" in a string of characters as represented inside a computer; rather, text is stored as a sequence of characters, each represented by specific codes according to encoding standards like ASCII or UTF-8.
Formatting, such as bold, italic, or underlined text, is not inherent to the string itself but is implicit in the way that string is interpreted by a terminal or editor or display engine (such as a web browser).
In Method 1, we use control characters to signify that "bold what comes after this". In Method 2, we are again using control characters but this time these control characters are determined by the library we have imported (namely, rich).
There is another library we can use in place of rich, which is the markdown library. Markdown is a lightweight markup language that allows you to format plain text in a simple and readable way. It was created by John Gruber in 2004. Once you write your content in Markdown, we can use Python libraries to convert the Markdown content into HTML or any other form that recognizes bold, italics, etc.
Here is some code that uses markdown. Note that this is Python code that generates HTML output:
import markdown
# Markdown text
md_text = """
# Markdown Example
This is regular text in Markdown
**This is bold text in Markdown!**
"""
# Convert Markdown to HTML
html_output = markdown.markdown(md_text)
# Display the HTML output
print(html_output)
If you run this program, the output will be:
<h1>Markdown Example</h1>
<p>This is regular text in Markdown
<strong>This is bold text in Markdown!</strong></p>
Note that the above is HTML content that if displayed in a browser will show you the bold content.
So what is the distinction between all these approaches?
In Method 1, the content and presentation are "mixed up". In other words, if you look at the string you are printing, you can see sometimes the content is a control character and sometimes it is actual content that is to be printed.
In Methods 2 and 3, we have "separation of content and presentation". They allow greater flexibility, enabling the same underlying text to be styled differently depending on the context or medium in which it is presented.
As a Python developer, you should understand these distinctions. Which approach you adopt depends on the end application in mind.
If you liked this blogpost, checkout our blogpost on how to pretty print JSON data structures in Python.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.