How to display text in Python
Learn how to display text in Python using various methods. Discover tips, real-world applications, and how to debug common errors.
.png)
The ability to display text is a core Python skill. It's essential for simple scripts and complex applications. The print() function is the primary tool to show simple output.
In this article, we'll explore techniques beyond basic output. You'll find tips on how to format text, explore real-world applications, and get advice to debug your code for clear communication.
Using the print() function
print("Hello, World!")
print("This is a simple text display in Python.")--OUTPUT--Hello, World!
This is a simple text display in Python.
The print() function is Python's standard for displaying output. Each time you call the function, it sends the given string to the console. You'll notice each string in the example appears on a new line.
This isn't an accident. The print() function automatically adds a newline character at the end of its output. This default behavior is designed for readability, making it simple to log sequential information without manually formatting line breaks.
Basic text display methods
While print() is great for static messages, you'll often need to combine text with variables, and Python provides a few key methods for this.
Using f-strings for dynamic text
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
print(f"Next year I will be {age + 1}.")--OUTPUT--My name is Alice and I am 30 years old.
Next year I will be 31.
F-strings, or formatted string literals, let you embed expressions directly inside string constants. You create one by prefixing a string with the letter f. This modern approach is often preferred for its readability and speed.
- Place variables directly inside curly braces
{}within the string. - You can also evaluate simple Python expressions, like
{age + 1}, right inside the braces.
Formatting with the .format() method
language = "Python"
version = 3.9
print("I am using {} version {}.".format(language, version))
print("{1} is the version of {0} I'm using.".format(language, version))--OUTPUT--I am using Python version 3.9.
3.9 is the version of Python I'm using.
Before f-strings became popular, the .format() method was the standard for string formatting. You call it on a string containing curly braces {} as placeholders. The arguments passed to .format() then fill these placeholders.
- By default, the arguments fill the placeholders in sequential order.
- You can also specify the order using index numbers like
{0}and{1}. This gives you more control over how the variables appear in the final string.
String concatenation for display
first_part = "Python"
second_part = "is powerful"
print(first_part + " " + second_part + "!")
print("Learning " + first_part + " " + "is fun.")--OUTPUT--Python is powerful!
Learning Python is fun.
String concatenation joins strings together using the + operator. It's a straightforward method for combining text and variables into a single output. While simple, it has a few quirks you should know.
- You must manually insert spaces, like
" ", between variables to prevent them from running together. - All parts must be strings. If you're working with numbers or other types, you'll need to convert them first using
str().
Advanced text display techniques
Beyond simple one-liners, Python offers powerful tools for managing multi-line text, wrapping long paragraphs, and even adding a splash of color to your output.
Multi-line text display
print("""This is a multi-line
text display in Python.
It preserves all line breaks.""")
message = "Line 1\nLine 2\nLine 3"
print(message)--OUTPUT--This is a multi-line
text display in Python.
It preserves all line breaks.
Line 1
Line 2
Line 3
Python offers two main approaches for displaying text across multiple lines. Wrapping your string in triple quotes (""") is often the simplest way, as it preserves the exact formatting and line breaks from your code. The alternative is to use the newline character (\n) inside a standard string.
- Triple quotes are ideal for static, pre-formatted blocks of text.
- The
\ncharacter gives you precise, manual control over where each new line begins.
Using the textwrap module for text formatting
import textwrap
long_text = "This is a very long text that we want to wrap to make it more readable when displayed in the console."
wrapped_text = textwrap.fill(long_text, width=40)
print(wrapped_text)--OUTPUT--This is a very long text that we want to
wrap to make it more readable when
displayed in the console.
The textwrap module is your go-to tool for formatting long paragraphs, especially when you need text to fit neatly into a console window. The textwrap.fill() function automatically breaks a long string into multiple lines to improve readability.
- You can control the maximum line length by setting the
widthargument. - This is perfect for ensuring your output is clean and easy to follow, regardless of the original text's length.
Using ANSI escape codes for colored text
RED = "\033[91m"
GREEN = "\033[92m"
RESET = "\033[0m"
print(f"{RED}This text is red!{RESET}")
print(f"{GREEN}This text is green!{RESET}")--OUTPUT--This text is red!
This text is green!
You can add color to your terminal output using ANSI escape codes. These are special character sequences that most modern terminals interpret as formatting instructions rather than text to display. This technique is great for making logs more readable by highlighting errors in red or success messages in green.
- Each code, like
\033[91m, tells the terminal to switch to a specific color. - It's essential to include a
RESETcode, such as\033[0m, to return the text to its default style. Otherwise, all subsequent output will remain colored. - Keep in mind that compatibility can vary, as not all terminals support these codes.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Describe what you want to build, and Agent 4 handles everything—from writing the code to connecting databases and APIs, to deploying it live.
Instead of piecing together techniques, describe the app you actually want to build and the Agent will take it from idea to working product:
- A log formatter that takes raw output and color-codes it for readability, highlighting errors in red.
- A text utility that wraps long paragraphs to a specified width, perfect for creating clean console readouts.
- A dynamic message generator that combines user data with a template to create personalized welcome messages.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with simple text display, you can run into a few common roadblocks that are easy to fix once you know what to look for.
- Avoiding
TypeError: You'll get aTypeErrorif you try to join strings and numbers with the+operator. Since Python doesn't automatically convert types during concatenation, you must wrap non-string variables instr(). Using f-strings is often a better choice, as they handle this conversion for you. - Debugging escaped characters: Sometimes special characters like
\n(newline) or\t(tab) don't behave as expected. If you need to print a literal backslash, like in a file path, you can either escape it with another backslash (\\) or use a raw string by prefixing it with anr. - Fixing indentation issues: Multi-line strings defined with triple quotes preserve all leading whitespace from your code. This can result in unwanted indentation in your output. The
textwrap.dedent()function is the perfect tool for cleaning this up by removing any common leading spaces.
Avoiding TypeError when mixing data types in print()
A common hurdle is the TypeError, which pops up when you try to combine different data types—like strings and numbers—using the + operator. Python requires all parts to be strings for concatenation. Check out the code below to see what happens.
age = 25
print("I am " + age + " years old.")
This code fails because the + operator cannot add the string "I am " to the integer age. Python requires compatible types for this operation. See the correct approach in the example below.
age = 25
print("I am " + str(age) + " years old.")
# Better alternative with f-strings:
print(f"I am {age} years old.")
The fix involves explicitly converting numbers to strings before concatenation. By wrapping the integer age in the str() function, you tell Python to treat it as text, resolving the TypeError. While this works, using an f-string like f"I am {age} years old." is often better. It's more readable and automatically handles the type conversion for you, which helps prevent this common error in the first place.
Debugging escaped characters in string output
Debugging escaped characters in string output
Escape characters give strings special formatting powers, like using \n for a new line. This can backfire when you need to print literal text, such as a file path, where backslashes have their own meaning. See what happens below.
file_path = "C:\new_folder\text_file.txt"
print(file_path)
Python interprets the backslashes as formatting codes, reading \n as a newline and \t as a tab. This scrambles the output. The code below demonstrates the correct way to display the literal path.
file_path = r"C:\new_folder\text_file.txt"
print(file_path)
# Alternative with escaped backslashes:
file_path = "C:\\new_folder\\text_file.txt"
print(file_path)
To print the path correctly, you have two options. You can prefix the string with an r to create a raw string, like r"C:\...". This tells Python to treat backslashes as literal characters instead of escape codes.
Alternatively, you can escape each backslash by doubling it up, such as "C:\\...". This is especially important when you're working with Windows file paths or regular expressions where backslashes have special meanings.
Fixing indentation issues in multi-line strings
Multi-line strings created with triple quotes are convenient, but they have a catch. They capture all leading whitespace from your code, which can lead to unwanted indentation in your output. This is especially common when defining strings inside functions.
Check out the code below. Notice how the output from the display_info() function includes extra spaces before each line, mirroring the indentation in the source code.
def display_info():
print("""
User Information:
Name: John Doe
Age: 30
""")
Since the multi-line string is indented inside the display_info() function, the output inherits that leading whitespace. This makes the text look misaligned. The following example shows how to remove this unwanted indentation for a clean display.
def display_info():
print("""User Information:
Name: John Doe
Age: 30""")
# Alternative approach with separate lines:
print("User Information:")
print("Name: John Doe")
print("Age: 30")
To fix the indentation, you must remove the leading whitespace from the string itself. The code shows two ways to do this. You can either left-align the entire triple-quoted string in your editor or use separate print() calls for each line.
This ensures the output isn't indented along with your function's code. This is a common issue when defining formatted text inside functions or classes, so always check your string's alignment.
Real-world applications
With these text display techniques mastered, you can build practical tools like command-line interfaces and formatted data reports.
Creating a simple command-line interface
You can build a clean and interactive menu for a command-line application by combining techniques like f-strings and loops to dynamically display a list of options.
menu_title = "Task Manager"
print(f"\n===== {menu_title} =====")
options = ["Add new task", "View all tasks", "Mark task as complete", "Exit"]
for i, option in enumerate(options, 1):
print(f"{i}. {option}")
selected = 2
print(f"\nYou selected: {options[selected-1]}")
This code builds a text-based menu by first printing a formatted title using an f-string. It then processes a list of strings called options to display the menu items.
- The
enumerate()function loops through the list, assigning a number to each option starting from1. - Inside the loop, an f-string prints each numbered option on a new line.
- Finally, it confirms a selection by accessing the list with an index of
selected-1, which correctly adjusts the user-facing number to the list's zero-based index.
Generating a formatted data report with .format()
The .format() method excels at producing structured reports, giving you fine-grained control over text alignment and number formatting for clean, readable output.
sales = {"Laptops": 15200, "Phones": 8400, "Accessories": 5100}
total = sum(sales.values())
print("\n" + "=" * 35)
print("{:^35}".format("SALES REPORT"))
print("=" * 35)
for product, amount in sales.items():
percentage = (amount / total) * 100
bar = "#" * int(percentage / 5)
print("{:<12} ${:<8,.2f} {:>4.1f}% {}".format(
product, amount, percentage, bar))
print("-" * 35)
print("{:<12} ${:<8,.2f}".format("TOTAL", total))
This script builds a formatted sales report from a dictionary. It leverages the .format() method with format specifiers to control the layout precisely. The code calculates total sales and then loops through each product to print a detailed line item.
- The specifiers, like
{:<12}, align text to the left within a fixed width. - Codes such as
{:<8,.2f}format numbers as currency with commas and two decimal places. - It even generates a simple bar chart by multiplying the
#string based on each product's sales percentage.
Get started with Replit
Now, turn these techniques into a real tool. Tell Replit Agent to "build a log formatter that colors errors red" or "create a script that wraps text to a specific width."
The Agent writes the code, tests for errors, and deploys your app. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)

.png)