Skip to content

Effortlessly Print New Line in Python

[

Your Guide to the Python print() Function

By Bartosz Zaczyński

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.

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() multiple times to create multiple blank lines.

Separating Multiple Arguments

Although your examples so far didn’t print anything exciting, the print() function is still capable of more. For example, you can use it to print multiple values in one go by separating them with commas:

>>> print('Hello', 'World')

This will print 'Hello World' with a space separating the two words.

Preventing Line Breaks

By default, print() adds a newline character (\n) at the end of each print statement. If you want to prevent this from happening, you can pass the end argument to print() and specify an empty string as its value:

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

This will print 'HelloWorld' without a space or newline character between the two words.

Printing to a File

So far, you’ve been using print() to write to the standard output, which is your terminal. However, you can also use it to write text to a file. To do that, you need to pass the file object as the first argument to print(), followed by the string you want to write:

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

This will create a new file named output.txt and write 'Hello, World!' to it.

Buffering print() Calls

By default, print() will buffer multiple calls and write the output all at once. If you want to force it to write the output immediately after each call, you can pass the flush argument to print() and set it to True:

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

This will ensure that the print statement is immediately written to the output.

Printing Custom Data Types

You’ve been using print() to print strings so far. However, you can also use it to print values of different data types, such as numbers or boolean values:

>>> print(42)
>>> print(True)

This will print the number 42 and the boolean value True, respectively.

Understanding Python print()

Now that you’re familiar with the basics of using print(), let’s take a closer look at how the function works and the differences between Python 2 and Python 3.

In Python 3, print() is a built-in function, meaning you can use it just like any other function. You can pass arguments to it, separate multiple arguments with commas, and modify its behavior using optional arguments.

In Python 2, print was not a function. Instead, it was a statement, which meant that you could call it without using parentheses:

print "Hello, World!"

This is one of the major differences between Python 2 and Python 3 and one of the reasons Python 3 introduced the print() function.

Printing With Style

Now that you have a good understanding of the basics, let’s explore some more advanced techniques for using print().

Pretty-Printing Nested Data Structures

print() can help you visualize complex data structures, such as lists or dictionaries, by pretty-printing them in a more readable format. To do that, you can use the pprint module from the Python standard library:

import pprint
data = [1, 2, [3, 4, [5, 6, 7], 8], 9]
pprint.pprint(data)

This will print the nested list in a more readable format, with each level of nesting indented and enclosed in square brackets.

Adding Colors With ANSI Escape Sequences

You can use ANSI escape sequences to add colors or other formatting to your print() output. For example, to print text in red, you can use the escape sequence \033[91m before the text you want to color and the escape sequence \033[0m after it to reset the formatting:

print('\033[91m' + 'Hello, World!' + '\033[0m')

This will print 'Hello, World!' in red.

Building Console User Interfaces

If you want to build more interactive programs, you can use print() to create a user interface in the terminal. For example, you can print a menu and ask the user for input:

print('1. Option 1')
print('2. Option 2')
print('3. Option 3')
choice = input('Select an option: ')

This will print a menu on the screen and ask the user to select an option by entering a number.

Living It Up With Cool Animations

Believe it or not, you can use print() to create animations in the terminal! By printing and clearing the output in a loop, you can create the illusion of movement. Here’s an example that prints a spinning loading icon:

import time
spinner = ['-', '\\', '|', '/']
for _ in range(10):
for character in spinner:
print(character, end='\r')
time.sleep(0.1)

This will create a spinner animation that appears to be spinning on the screen.

Making Sounds With print()

Yes, you read that right! You can actually make sounds using print() in Python. By printing the ASCII codes for the specific sound frequencies, you can generate simple audio effects. For example, here’s how you can play a beep sound:

print('\a')

This will produce a beep sound, although the actual audio output may vary depending on your operating system and hardware configuration.

Mocking Python print() in Unit Tests

When writing unit tests, you might want to prevent print() statements from cluttering your test output. You can do this by mocking print() and redirecting its output to a variable. This allows you to assert that the expected output was printed without actually displaying it on the screen.

import io
from unittest.mock import patch
def my_function():
print('Hello, World!')
with patch('sys.stdout', new=io.StringIO()) as fake_stdout:
my_function()
assert fake_stdout.getvalue() == 'Hello, World!\n'

This will mock the print() function and redirect its output to the fake_stdout variable. You can then assert that the expected output was printed.

print() is a powerful tool for debugging. By strategically placing print() statements in your code, you can inspect the values of variables at different stages of execution and identify any bugs or errors.

Tracing

One common debugging technique is to trace the execution of your code by printing messages at key points. For example, you might print a message every time a certain function is called or a loop iterates:

for i in range(10):
print(f'Iteration {i}')
def my_function():
print('Function call')
my_function()

This will print the iteration number for each loop iteration and a message every time my_function() is called.

Logging

Instead of using print() statements for debugging, you can use the logging module from the Python standard library. This provides more advanced logging capabilities, such as logging to files, formatting log messages, and easily enabling or disabling logging depending on your needs.

import logging
logging.basicConfig(level=logging.INFO)
logging.info('This is an informational message')

This will configure the logging system to log informational messages and print the message to the console.

Debugging

If you’re using a development environment, such as PyCharm or Visual Studio Code, you can take advantage of built-in debugging tools. These tools allow you to set breakpoints in your code, inspect variables, and step through your code line by line.

When using a debugger, you can set breakpoints directly in your code and run your program in debug mode. When the program reaches a breakpoint, execution will pause, allowing you to inspect variables and step through the code.

Thread-Safe Printing

If you’re working with multiple threads in your program, you need to be careful when using print() to avoid conflicts between threads. print() is not inherently thread-safe and can produce unexpected results when called from multiple threads simultaneously.

To ensure thread safety, you can use synchronization mechanisms, such as locks or semaphores, to coordinate access to the print() function.

Python print() Counterparts

Besides Python’s built-in print() function, there are also third-party libraries available that provide additional functionality and features for printing. Some popular ones include:

  • pprint: A built-in module for pretty-printing data structures.
  • colorama: A library for adding colors and styles to terminal output.
  • tabulate: A library for producing formatted tables.
  • rich: A library for creating rich terminal output with colors, styles, and emojis.

Be sure to explore these libraries for more advanced printing techniques.

Conclusion

You have now learned the ins and outs of the Python print() function. From basic printing to advanced formatting and debugging, print() is a versatile tool that every Python programmer should master. Armed with this knowledge, you can take your Python programming skills to the next level and create more interactive and dynamic programs.

So why wait? Start experimenting with print() and unleash its full potential in your Python projects!