Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

The power of Python's print function PREMIUM

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
4 min. read Python 3.9—3.13
Tags

Python's print function is usually one of the first built-in functions that new Pythonistas learn about, but many Python programmers don't realize how versatile the print function is.

Let's look at some of the secret powers of Python's print function.

Using multiple arguments

Python's print function can accept more than one argument:

>>> count = 4
>>> print("There are", count)
There are 4

Python's f-strings pair very nicely with the print function.

>>> count = 4
>>> total = 8
>>> print(f"{count} out of {total} is {count/total:.0%}.")
4 out of 8 is 50%.

But keep in mind that the print function also accepts multiple arguments. So if you're just putting spaces between a couple variables/strings:

>>> language = "English"
>>> print(f"Current language: {language}")

You could pass multiple arguments to print instead:

>>> language = "English"
>>> print("Current language:", language)

Python's f-strings are great, but if you just need to smoosh a few values together with spaces between them, consider passing separate arguments to print.

Unpacking an iterable into print

Python's print function doesn't just accept more than one argument, it accepts any number of positional arguments.

So if we wanted to print every item in a list, we could use the * operator to pass that list to print:

>>> arguments = ["4", "5", "8", "--sum"]
>>> print(*arguments)
4 5 8 --sum

This doesn't just work on lists. It works for any iterable. For example we could unpack a generator object into print to see each value in it:

>>> numbers = [2, 1, 3, 4, 7, 11]
>>> squares = (n**2 for n in numbers)
>>> print(*squares)
4 1 9 16 49 121

Using print instead of the string join method

Why bother using * when you could just use the string join method?

>>> print(" ".join(arguments))
4 5 8 --sum

Well, it's a little bit shorter to write but it's also more flexible.

Let's say we'd like to print numbers with spaces between each one. If we use the join method we'll get an error when joining numbers together:

>>> numbers = [2, 1, 3, 4, 7, 11]
>>> print(" ".join(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

We need to convert each item to a string to join them. We could use a list comprehension or a generator expression for that:

>>> print(" ".join(str(n) for n in numbers))
2 1 3 4 7 11

But the print function does this conversion automatically:

>>> print(*numbers)
2 1 3 4 7 11

The print function will automatically convert whatever object you give it to a string because it needs to be a string in order to be printed.

Customizing the sep value

What if you'd like to join your values together by something that isn't a space character? For example let's say we have a list of strings and we'd like to print each string with newline characters between them. We could use the join method:

>>> colors = ["purple", "green", "blue", "yellow"]
>>> print("\n".join(colors))
purple
green
blue
yellow

Or we could use the print function's optional sep argument:

>>> print(*colors, sep="\n")
purple
green
blue
yellow

The sep argument defaults to a space character, but we can set it to any string we'd like. For example we could make it a comma followed by a space character:

>>> print(*colors, sep=", ")
purple, green, blue, yellow

Combining the use of * with the sep argument makes the print function a pretty good replacement for the string join method in most cases.

Printing to a file

The print function is handy for showing output at the terminal, but that's not its only use. In fact, the print is really a helper function for writing to a file object, but the default file it prints to is standard output.

You can customize which file-like object print will write to by specifying a file argument. For example here we're printing to standard error:

>>> import sys
>>> print("This is an error!", file=sys.stderr)
This is an error!

And here we're printing to an actual file:

with open("hello.txt", mode="w") as file:
    print("Hello world!", file=file)

I often prefer to print to files instead of manually calling the file write method because then I don't need to worry about converting objects to strings and making sure I add a newline character at the end of each line.

Customizing the end value

What if you want to print something, but you don't want it to print all on its own line?

By default the print function writes a newline at the end of everything else you've called it with. But print accepts an optional end argument that we can use to customize that behavior:

>>> help(print)
Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.

    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
    file
      a file-like object (stream); defaults to the current sys.stdout.
    flush
      whether to forcibly flush the stream.

For example here's a print call that prints two newline characters instead:

>>> print("This will have two newlines after it", end="\n\n")
This will have two newlines after it

And here we've printed to a file without adding a newline at the end and then we printed again to put something else on the same line:

>>> numbers = [2, 1, 3, 4, 7, 11, 18]
>>> with open("data.txt", "w") as file:
...     print("Lucas numbers: ", end="", file=file)
...     print(*numbers, sep=", ", file=file)
...

So the file will look like this afterward:

Lucas numbers: 2, 1, 3, 4, 7, 11, 18

Using print is a file-writing utility tool

The print function is a utility function that makes it easier to write data to files. It just so happens that the default file object that print writes to is standard output, which actually prints to the screen instead of writing to a file.

The print function is particularly handy for:

  • Writing to a file while adding newlines to the end of each line and converting any non-strings to strings before writing
  • Joining iterables together by any separator string, while converting any non-strings in the iterable to strings

The next time you want to join data together to display it in a terminal or write it to a file, think about using print.

This is a free preview of a premium article. You have 2 previews remaining.