Skip to content

Effortlessly Print New Lines in Python

[

Your Guide to the Python print() Function

If you’re like most Python users, including me, then you probably started your Python journey by learning about print(). It helped you write your very own hello world one-liner. You can use it to display formatted messages onto the screen and perhaps find some bugs. But if you think that’s all there is to know about Python’s print() function, then you’re missing out on a lot!

Keep reading to take full advantage of this seemingly boring and unappreciated little function. This tutorial will get you up to speed with using Python print() effectively. However, prepare for a deep dive as you go through the sections. You may be surprised how much print() has to offer!

By the end of this tutorial, you’ll know how to:

  • Avoid common mistakes with Python’s print()
  • Deal with newlines, character encodings, and buffering
  • Write text to files
  • Mock print() in unit tests
  • Build advanced user interfaces in the terminal

If you’re a complete beginner, then you’ll benefit most from reading the first part of this tutorial, which illustrates the essentials of printing in Python. Otherwise, feel free to skip that part and jump around as you see fit.

Note: print() was a major addition to Python 3, in which it replaced the old print statement available in Python 2. There were a number of good reasons for that, as you’ll see shortly. Although this tutorial focuses on Python 3, it does show the old way of printing in Python for reference.

Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Printing in a Nutshell

Let’s jump in by looking at a few real-life examples of printing in Python. By the end of this section, you’ll know every possible way of calling print(). Or, in programmer lingo, you’d say you’ll be familiar with the function signature.

Calling print()

The simplest example of using Python print() requires just a few keystrokes:

>>> print()

You don’t pass any arguments, but you still need to put empty parentheses at the end, which tell Python to actually execute the function rather than just refer to it by name.

This will produce an invisible newline character, which in turn will cause a blank line to appear on your screen. You can call print() without any arguments if you just want to print an empty line.

Separating Multiple Arguments

The true power of print() comes when you have multiple arguments that you want to display. Python automatically separates arguments with a single space:

>>> print("Hello", "World")
Hello World

In this example, Python inserts a space character between "Hello" and "World". You can pass as many arguments as you want, and all of them will be printed in order, separated by spaces.

Preventing Line Breaks

By default, print() adds a newline character at the end of the printed text. This means that each call to print() will start writing on a new line. If you don’t want this behavior, you can use the end parameter to specify a different ending character:

>>> print("Hello", end=" ")
>>> print("World")
Hello World

In this example, the end parameter is set to a space character. This tells print() to use a space instead of a newline character as the ending character. As a result, the next call to print() will continue on the same line instead of starting a new line.

Printing to a File

Besides the standard output, you can also redirect the output of print() to a file. The file parameter allows you to specify the file object to which the text should be written:

>>> with open("output.txt", "w") as f:
... print("Hello, World!", file=f)
...

In this example, a file named “output.txt” is opened in write mode and assigned to the variable f. The print() function is called with the file parameter set to f, which causes the text to be written to the file instead of being displayed on the screen.

Buffering print() Calls

In certain situations, you may want to control the buffering behavior of print(). By default, print() uses a line-buffered mode, which means it only flushes the output buffer when it encounters a newline character. However, you can change this behavior by using the flush parameter:

>>> print("Hello", flush=True)

In this example, the flush parameter is set to True, which forces the output buffer to be flushed immediately after printing the argument. This can be useful if you want to ensure that the printed text is immediately visible rather than waiting for a newline character.

Printing Custom Data Types

print() can handle custom data types as well. When you pass an object of a custom class to print(), Python automatically calls the object’s __str__() method to convert it to a string representation:

>>> class Person:
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
... def __str__(self):
... return f"Person(name={self.name}, age={self.age})"
...
>>> person = Person("Alice", 25)
>>> print(person)
Person(name=Alice, age=25)

In this example, the Person class defines a __str__() method that returns a string representation of the object. When the print() function is called with an instance of the Person class, it automatically calls the __str__() method to get the string representation.

Understanding Python print()

To fully understand how to use print() effectively, it’s important to have a good grasp of how it works under the hood. This section will cover the internals of the print() function in Python.

In Python 3, print() is a built-in function, whereas in Python 2, print was a statement. This change was made to improve consistency and to make Python more modular and extensible.

As a function, print() can be called with parentheses and arguments, following the typical function-call syntax.

In Python 2, print was a statement that didn’t require parentheses. This led to some confusion and inconsistencies, especially when dealing with Python 3 code.

Here’s an example of how print was used as a statement in Python 2:

>>> print "Hello, World!"
Hello, World!

As you can see, the message to be printed is placed directly after the print statement, without any parentheses. This different syntax can cause issues if you’re trying to run Python 3 code in a Python 2 environment.

Printing With Style

Printing isn’t just about displaying text on the screen. With some additional techniques, you can make your printed output more visually appealing and interactive. This section will cover various ways to enhance the output of the print() function.

Pretty-Printing Nested Data Structures

When dealing with complex data structures, such as lists or dictionaries, it can be difficult to visualize their contents in a clear and readable manner. The pprint module provides a useful alternative to the standard print() function, allowing you to pretty-print nested data structures:

>>> from pprint import pprint
>>> data = {
... "name": "Alice",
... "age": 25,
... "favorites": {
... "color": "blue",
... "food": "pizza",
... "sport": "soccer"
... }
... }
>>> pprint(data)
{
'name': 'Alice',
'age': 25,
'favorites': {
'color': 'blue',
'food': 'pizza',
'sport': 'soccer'
}
}

In this example, the pprint() function is used to print the data dictionary in a more structured and visually appealing way. The output is indented and includes line breaks, making it easier to understand the structure of the nested data.

Adding Colors With ANSI Escape Sequences

In some cases, you may want to add colors or other formatting styles to your printed output. This can be achieved using ANSI escape sequences, which are special characters that control how the text is displayed on the terminal:

>>> print("\033[1;33;41mThis is a formatted string\033[0m")

In this example, the print() function is called with a string that contains ANSI escape sequences. These escape sequences start with the character \033 (also known as the Escape character) and are followed by specific codes that represent different text styles, colors, and other formatting options.

Building Console User Interfaces

With the help of the curses module, you can create more sophisticated console user interfaces. This can be useful for building command-line tools or text-based games. The curses module provides a higher level of control over the terminal, allowing you to manipulate text, colors, and screen positions:

>>> import curses
>>> stdscr = curses.initscr()
>>> stdscr.addstr(0, 0, "Hello, World!")
>>> stdscr.refresh()
>>> stdscr.getch()
>>> curses.endwin()

In this example, the curses module is used to initialize the terminal, add a string to the screen, refresh the screen, wait for user input, and finally release the terminal. This simple example demonstrates the basics of building a console user interface using curses.

Living It Up With Cool Animations

With a combination of Unicode characters and some creativity, you can even create simple animations in the terminal. By printing a series of frames at regular intervals, you can give the illusion of movement:

>>> import time
>>> animation_frames = ["", "", "", "", "", "", "", ""]
>>> for frame in animation_frames:
... print(frame, end="\r")
... time.sleep(0.2)
...

In this example, a list of Unicode characters is used to represent different frames of the animation. By printing each frame in succession and adding a small delay in between, the frames appear to animate when viewed in the terminal.

Making Sounds With print()

Yes, you read that right. You can actually make sounds with the print() function in Python, thanks to the pygame library:

>>> import pygame
>>> pygame.mixer.init()
>>> pygame.mixer.music.load("sound.wav")
>>> pygame.mixer.music.play()
>>> while pygame.mixer.music.get_busy():
... pass
>>> pygame.mixer.quit()

In this example, the pygame library is used to load and play a sound file. The sound file is specified by its filename, which can be a WAV, MP3, or other supported audio file format. Once the sound is playing, the program waits until it finishes before exiting.

Mocking Python print() in Unit Tests

In some cases, you may want to test a function or class that uses the print() function internally. However, including the output of print() in your test results can be cumbersome and may clutter the test output. To solve this problem, you can temporarily replace the standard output with a custom file-like object:

>>> from io import StringIO
>>> import sys
>>>
>>> def my_function():
... print("Hello, World!")
...
>>> stdout = sys.stdout
>>> sys.stdout = StringIO()
>>> my_function()
>>> output = sys.stdout.getvalue().strip()
>>> sys.stdout = stdout
>>>
>>> print(output)
Hello, World!

In this example, the my_function() function includes a print() statement that writes to the standard output. To capture the output instead of printing it to the terminal, the sys.stdout object is temporarily replaced with a StringIO object, which allows the output to be stored in a string. After the function is called, the captured output is extracted from the StringIO object and can be used for testing purposes.

In addition to providing a convenient way to display information during program execution, print() can also be used as a debugging tool. This section will cover several techniques for using print() to debug your Python code.

Tracing

One common use of print() in debugging is to trace the flow of execution through a program. By placing print() statements at various locations in your code, you can see which parts of the code are being executed and in what order:

def my_function():
print("Entering my_function")
# ... some code ...
print("Before return")
return result
print("Before function call")
result = my_function()
print("After function call")

In this example, print() statements are added before and after the function call, as well as inside the function. By examining the order in which the statements are printed, you can get a better understanding of the flow of execution through the program.

Logging

A more flexible and powerful alternative to using print() for debugging is the logging module. The logging module provides a way to write diagnostic messages to a file or the console, along with various levels of severity and formatting options:

import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger("my_module")
def my_function():
log.debug("Entering my_function")
# ... some code ...
log.debug("Before return")
return result
log.debug("Before function call")
result = my_function()
log.debug("After function call")

In this example, the logging module is used to create a logger object named “my_module”. Logging statements are added at various locations in the code using the log.debug() function. The logging level is set to DEBUG, which means all logging statements will be printed to the console. By adjusting the logging level, you can control which messages are displayed and which are ignored.

Debugging

For more advanced debugging needs, Python provides a built-in debugger called pdb. The pdb module allows you to pause the execution of your program at any point and interactively explore the state of the program, set breakpoints, and step through the code:

import pdb
def my_function():
# ... some code ...
pdb.set_trace()
# ... more code ...
result = my_function()

In this example, the pdb.set_trace() function is called inside the my_function() function. When the program reaches this point, it will pause and start the interactive debugger. From there, you can examine the values of variables, execute code line by line, and navigate through the program to find and fix bugs.

Thread-Safe Printing

If you’re working with multiple threads in your Python program, you may encounter issues with concurrent access to the standard output. To ensure that printing from multiple threads is thread-safe, you can use a lock object to synchronize access to the print() function:

import threading
def my_function():
with threading.Lock():
print("Hello, World!")

In this example, the threading.Lock() object is used to create a lock that can be acquired and released by different threads. By using the with statement, the lock is automatically acquired at the beginning of the block and released at the end, ensuring that only one thread can execute the print() function at a time.

Python Print Counterparts

While the print() function is the most common way to display text in Python, there are also other functions and libraries that can achieve similar results. This section will briefly cover some of the built-in and third-party alternatives to the print() function.

Built-In

Python provides several built-in functions that can be used to display text and data. Some of the most commonly used functions include:

  • sys.stdout.write(): Writes a string to the standard output without adding a newline character.
  • sys.stderr.write(): Writes a string to the standard error stream without adding a newline character.
  • repr(): Returns a string representation of an object, including its type and attribute values. This function is often used for debugging purposes.
  • str(): Converts an object to a string representation. This function is similar to repr(), but it doesn’t include the type and attribute values.

Third-Party

In addition to the built-in functions, there are also several third-party libraries that can be used to format and display text in Python. Some popular examples include:

  • tabulate: Provides a way to create formatted tables from tabular data.
  • rich: Offers extensive formatting and styling options, including colors, text backgrounds, and inline images.
  • termcolor: Allows you to add colors and formatting to text printed to the terminal.
  • colorama: Provides cross-platform support for colored terminal output by wrapping ANSI escape sequences.

Conclusion

In this tutorial, you learned how to use Python’s print() function effectively. You explored various techniques for controlling the output, adding formatting and colors, building user interfaces, and using print() for debugging purposes. With the knowledge gained from this tutorial, you can now take full advantage of the power and versatility of the print() function in your Python programs.

Keep in mind that print() is just one tool in your debugging and output arsenal. Depending on your specific needs, you may find other functions, libraries, or techniques to be more suitable. Always consider the requirements and constraints of your project, and choose the approach that best fits your use case.

Now that you have a solid understanding of the print() function, go forth and print with confidence in your Python programs!