Dr. Roger Ianjamasimanana

The Python print() function and string formatting

By Dr. Roger Ianjamasimanana

1. Understanding the Python print() function and string formatting

The print() function in Python outputs data to the console and is very versatile when combined with string formatting techniques. In Python, we can format strings using different methods: old-style % formatting, the str.format() method, and f-strings. Each method provides a way to embed variables and expressions within strings and controls the appearance of the output.

2. The print() function basics

The Python print() function can take any number of arguments, converting them to their textual representation and outputting them on a single line, separated by spaces by default. After printing the provided arguments, it appends a newline character \n, moving the cursor to the next line.

For example:

Notice that calling print() without arguments simply outputs a newline.

3. Standard output (stdout) and the print() function

Every running program communicates with the outside world through various channels. One of the most common channels in console-based applications is "standard output" (stdout). Stdout is simply a text output stream where your program sends its output.

In Python, the print() function writes data to stdout. Every time you call print(), the provided arguments are converted to string and appended to the output, typically followed by a newline character. This makes stdout a sequential stream of text lines.

When running a Python program from a terminal, stdout is the area where all output appears. For instance, suppose we have a file named hello.py containing the following lines:

print("Hello there")
print("How are you?)
print("I am fine")

Executing python hello.py on the terminal prints the content of each print function on a new line.

$ python3 hello.py
Hello there
How are you?
I am fine
$

4. Old-style string formatting with the % operator

Before Python 3.6 introduced f-strings, a common way to format strings was using the % operator. With this method, placeholders like %d, %f, and %s are used within a string, and their corresponding values are provided in a tuple after the % symbol.

For example, consider the following code snippet:

In this code:

  • The variables a, b, and name store an integer, a float, and a string respectively.
  • sum_value and product_value demonstrate arithmetic operations.
  • The print() function uses the % operator for formatting. Here, %d formats an integer, while %.2f formats a float to two decimal places. The placeholders in the string are replaced by the corresponding values in the tuple (a, b, product_value).

The old-style % formatting supports various specifiers:

  • %d: formats an integer.
  • %f: formats a float. For example, %.2f limits the float to two decimal places.
  • %s: formats a string.
These specifiers allow precise control over how values are displayed.

5. Modern string formatting with str.format()

Python's str.format() method provides a more powerful and flexible way to format strings. It uses curly braces {} as placeholders, which can be filled with variables passed to the format() method.

Notice how 1.232 became 1.23 because we have used two decimal point precision.

In this code snippet:

  • The curly braces {} act as placeholders.
  • Inside the braces, format specifiers such as {:.2f} work similarly to %.2f in old-style formatting.
  • The format() method substitutes the placeholders with the provided values (a, b, product_value).

6. Formatted string literals (f-strings)

The f-strings formatting was introduced in Python 3.6 and provides a concise way to embed expressions inside string literals. By prefixing a string with f, you can include variables directly inside curly braces. This method is often more readable and efficient.

Explanation:

  • By prefixing the string with f, we can directly embed variables and expressions inside curly braces.
  • {a} inserts the value of a, and {b:.2f} formats b as a float with 2 decimal places.
  • This method is straightforward and often preferred for its readability and efficiency.

7. Using the sep= and end= parameters

By default, print() separates arguments with spaces (sep=' ') and ends with a newline (end='\n'). However, you can change these behaviors using the optional sep= and end= parameters.

The sep= parameter defines how multiple arguments are separated:

Similarly, the end= parameter determines what is printed at the end of the output instead of the default newline:

Using end='' prevents print() from adding an extra newline, which is useful when your string already ends with one.

8. Print vs. return

While print() is great for displaying information to the user or debugging, it's important to differentiate it from a function's return value. A function's return value is meant for further processing in code, whereas print() simply sends output to stdout. In good program design, primary data flow should rely on return values, while print() should be used for user-facing messages or debugging.

9. Printing to a file

Besides standard output, Python's print() function can direct its output to a file by using the file= parameter. By opening a file in write mode and passing the file object to print(), you can write formatted text into that file.

filename = "output.txt"
with open(filename, 'w') as f:
    print('Hello world', file=f)

This will write Hello world to the output.txt file. Let's demonstrate it in the following code. First, we create a directory using the os.makedirs syntax, then write a file to that directory containing "Hello world". We then read the content of that file and print it.

In this snippet:

  • The file output.txt is opened for writing. If it exists, its content is erased.
  • print('Hello world', file=f) writes the text "Hello world" to that file, rather than to the standard output.

10. Conclusion

The print() function combined with various string formatting methods in Python allows for flexible and readable output. Whether using the old-style % operator, str.format(), or f-strings, each approach offers a way to format strings according to specific needs. Understanding these methods helps create clear and maintainable code, especially when presenting results or debugging.

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access