Python Programming Language



First published on October 10, 2019. Last updated on February 16, 2020.

Formatting in Python is not simple. However, it is not so bad, once you get the hang of it. Further, the way to format Python output has changed in newer versions of Python, so some examples online might be out of date. (However, the old approach may still work for your purposes, and there are some reasons to still use the old approach). We will show the new approach here. (If it doesn’t work for you, web search the old approach).

Simple Approach

The simplest approach to Python output is that which we have already used: the print statement. Remember that items must be separated by a comma, and text strings must be enclosed in single quotes.

print 'These are my result:', x, y, z

More Advanced Formatting—Old Method

The old method is discouraged, but sometimes it is just too useful to pass up. It is useful for formatting short strings and numbers, especially for the rows and columns of scientific computations in a loop.

The approach is to state a string, with format expression for the variables, then stating the variables. You assign the formatted string to a new variable, then state the new variable.

Here is an example:

annualGrain = 500849.37865
mystring = 'Annual grain production is: ' % 6.2f (annualGrain)

Which will output:

Annual grain production is: 500849.38

Note how the last three decimal places are rounded off, because out formatting only specified two decimal placed. See Formatting Strings in Further Reading below for more information about this approach.

New Method

Sometimes the simple print method is insufficient for your output or display requirements. In that case, you will need Python’s more advanced output formatting features.

The formatting statement comprises two parts: placeholders for the content and the content itself. Placeholders are a {} for each content item, all of which are enclosed together in single quotes. The placeholders are followed by a “.format” followed by the content items separated by commas, all enclosed together in parentheses. Here is an example:


Further Reading





Content is copyright the author. Layout is copyright Mark Ciotola. See for further notices.