Skip to content

Python Print Statement

Mastering the Art of Printing in Python

Printing in Python is more than just putting words on the screen; it’s a fundamental aspect of communicating with your program’s users and developers alike. In this comprehensive guide, we’ll explore the various ways you can use the print()print() function to display information, format output, and enhance the user experience.

Basics of Print in Python

print()print()

At its simplest, the print()print() function is used to display text or variables on the screen. Here’s a basic example:

print.py
print("Hello, Python!")
print.py
print("Hello, Python!")

Output:

command
C:\Users\Your Name> python print.py
Hello, Python!
command
C:\Users\Your Name> python print.py
Hello, Python!

This single line of code outputs the phrase “Hello, Python!” to the console. You can use single or double quotes to define strings within the print()print() function.

Formatting Text

Concatenation

You can concatenate multiple strings or variables within the print()print() function:

print.py
name = "Alice"
print("Hello, " + name + "!")
print.py
name = "Alice"
print("Hello, " + name + "!")

Output:

command
C:\Users\Your Name> python print.py
Hello, Alice!
command
C:\Users\Your Name> python print.py
Hello, Alice!

String Interpolation

String interpolation, also known as f-strings (formatted string literals), provides a more concise and readable way to format strings:

print.py
name = "Bob"
age = 30
print(f"{name} is {age} years old.")
print.py
name = "Bob"
age = 30
print(f"{name} is {age} years old.")

Output:

command
C:\Users\Your Name> python print.py
Bob is 30 years old.
command
C:\Users\Your Name> python print.py
Bob is 30 years old.

F-String Format Specifiers

F-strings can do much more than insert values — a :: inside the braces starts a format specifier that controls width, alignment, decimal places, and more.

fstring_format.py
pi = 3.14159
price = 1234.5
ratio = 0.875
 
print(f"{pi:.2f}")       # 3.14    -> 2 decimal places
print(f"{price:,.2f}")   # 1,234.50 -> thousands separator
print(f"{ratio:.1%}")    # 87.5%   -> percentage
print(f"{42:05d}")       # 00042   -> pad with zeros to width 5
print(f"{'hi':>10}")     # '        hi' -> right-align in 10 cols
fstring_format.py
pi = 3.14159
price = 1234.5
ratio = 0.875
 
print(f"{pi:.2f}")       # 3.14    -> 2 decimal places
print(f"{price:,.2f}")   # 1,234.50 -> thousands separator
print(f"{ratio:.1%}")    # 87.5%   -> percentage
print(f"{42:05d}")       # 00042   -> pad with zeros to width 5
print(f"{'hi':>10}")     # '        hi' -> right-align in 10 cols

You can also print the expression and its value with a trailing == (great for debugging):

fstring_debug.py
x = 10
print(f"{x = }")   # x = 10
fstring_debug.py
x = 10
print(f"{x = }")   # x = 10

String Formatting

The format()format() method allows for more controlled string formatting:

print.py
name = "Charlie"
age = 25
print("{} is {} years old.".format(name, age))
print.py
name = "Charlie"
age = 25
print("{} is {} years old.".format(name, age))

Output:

command
C:\Users\Your Name> python print.py
Charlie is 25 years old.
command
C:\Users\Your Name> python print.py
Charlie is 25 years old.

Controlling the Print Function

Changing the Separator

By default, the print()print() function separates items with a space. You can change this using the sepsep parameter:

print.py
print("One", "Two", "Three", sep="-")
print.py
print("One", "Two", "Three", sep="-")

Output:

command
C:\Users\Your Name> python print.py
One-Two-Three
command
C:\Users\Your Name> python print.py
One-Two-Three

Specifying the End Character

The endend parameter defines the character at the end of the print()print() function:

print.py
print("This is a line", end=".\n")
print.py
print("This is a line", end=".\n")

Output:

command
C:\Users\Your Name> python print.py
This is a line.
command
C:\Users\Your Name> python print.py
This is a line.

Another Example

print.py
print("This is a line", end="")
print("This is another line")
print.py
print("This is a line", end="")
print("This is another line")

Output:

command
C:\Users\Your Name> python print.py
This is a lineThis is another line
command
C:\Users\Your Name> python print.py
This is a lineThis is another line

In this example, we’ve used the endend parameter to remove the newline character from the first print()print() function. This allows us to print the second line on the same line as the first.

Diagram:

diagram print() parameters mermaid
How sep, end, and file shape the output

Unpacking a List into print

The ** operator unpacks an iterable so each element becomes a separate argument — combine it with sepsep to format collections neatly:

unpack_print.py
fruits = ["apple", "banana", "cherry"]
print(*fruits, sep=", ")   # apple, banana, cherry
unpack_print.py
fruits = ["apple", "banana", "cherry"]
print(*fruits, sep=", ")   # apple, banana, cherry

Printing to Standard Error

By default print()print() writes to standard output. Pass file=sys.stderrfile=sys.stderr to send messages to the error stream instead — useful for warnings and logs that should not mix with normal output. The flush=Trueflush=True argument forces the output to appear immediately.

stderr.py
import sys
print("Normal result")
print("Something went wrong", file=sys.stderr)
print("Loading...", end="", flush=True)   # appears at once, no buffering
stderr.py
import sys
print("Normal result")
print("Something went wrong", file=sys.stderr)
print("Loading...", end="", flush=True)   # appears at once, no buffering

Printing Variables and Expressions

You can print the values of variables and the result of expressions directly within the print()print() function:

print.py
x = 5
y = 10
print("The sum of {} and {} is {}.".format(x, y, x + y))
print.py
x = 5
y = 10
print("The sum of {} and {} is {}.".format(x, y, x + y))

Output:

command
C:\Users\Your Name> python print.py
The sum of 5 and 10 is 15.
command
C:\Users\Your Name> python print.py
The sum of 5 and 10 is 15.

Redirecting Output

Besides printing to the console, you can redirect the output to a file. This is particularly useful when logging information or capturing program output:

print.py
with open("output.txt", "w") as f:
    print("Redirecting output to a file.", file=f)
print.py
with open("output.txt", "w") as f:
    print("Redirecting output to a file.", file=f)

Output:

command
C:\Users\Your Name> python print.py
command
C:\Users\Your Name> python print.py
output.txt
Redirecting output to a file.
output.txt
Redirecting output to a file.

Advanced Printing Techniques

Pretty Printing with pprint

pprint()pprint()

The pprintpprint module provides a way to pretty-print data structures, enhancing readability:

print.py
from pprint import pprint
 
data = {"name": "David", "age": 28, "city": "Techland"}
pprint(data)
print.py
from pprint import pprint
 
data = {"name": "David", "age": 28, "city": "Techland"}
pprint(data)

Output:

command
C:\Users\Your Name> python print.py
{'age': 28, 'city': 'Techland', 'name': 'David'}
command
C:\Users\Your Name> python print.py
{'age': 28, 'city': 'Techland', 'name': 'David'}

ANSI Escape Codes for Colored Output

You can use ANSI escape codes to add color to your output for improved visual distinction:

print.py
print("\033[1;31mError:\033[0m Something went wrong.")
print.py
print("\033[1;31mError:\033[0m Something went wrong.")

Output:

command
C:\Users\Your Name> python print.py
Error: Something went wrong.
command
C:\Users\Your Name> python print.py
Error: Something went wrong.

Conclusion

Mastering the art of printing in Python is about more than just displaying text. It’s about effectively communicating information, enhancing readability, and creating a positive user experience. Whether you’re a beginner or an experienced developer, understanding the nuances of the print()print() function and exploring advanced printing techniques can significantly impact the quality of your Python programs.

Experiment with the examples provided, try different formatting options, and explore advanced printing features to elevate your Python coding skills. Happy printing, and may your Python output always be clear, concise, and visually appealing!

For more insights and practical examples, delve into our tutorials on Python Central Hub!


Try it: Print Exercises

Exercise 1 – Basic Print

Exercise 2 – F-String Formatting

Exercise 3 – Print with sep and end

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did