One of the important methods in class str is str.format(). It applies formatting and variable substitution to a given string.. The string is filled in with the supplied set of arguments, according to format rules. In the following simple example, the positional placeholders {} are replaced with the the arguments 'Joe' and 'Hello'.

>>> "Hi, I'm {}, and I say {}".format('Joe','Hello')
"Hi, I'm Joe, and I say Hello"
Python

We use double quotes around the string because it contains an apostrophe (although we could also have escaped the apostrophe with a backslash, i.e., \'). The curly braces {} represent the replacement fields. They are replaced by the input parameters in positional order.

We can also assign a number to each replacement field, indicating the desired order of the arguments that are passed into the str.format() method.

>>> "Hi, I'm {0}, and I say {1}".format('Joe','Hello')
"Hi, I'm Joe, and I say Hello"
>>> "Hi, I'm {1}, and I say {0}".format('Joe','Hello')
"Hi, I'm Hello, and I say Joe"
Python

Alternatively, we can assign keywords to the positional variables. The corresponding inputs ('Joe' and 'Hello', in this case) are substituted accordingly.

>>> "Hi, I'm {n}, and I say {g}".format(n='Joe',g='Hello')
"Hi, I'm Joe, and I say Hello"
Python

Arguments that are of a numerical type will automatically be converted into strings.

>>> mypi = 3.14159265
>>> 'PI = {}'.format(mypi)
'PI = 3.14159265'
Python

To control the formatting of numbers, we use the optional colon or : symbol. It allows us to specify the number of digits to be included in the output string, for instance.

>>> 'PI = {0:.5f} to 5 decimal places'.format(3.14159265)
'PI = 3.14159 to 5 decimal places'
Python

If you prefer, you can specify format the old-fashioned way, similar to I/O formatting in C. In this convenient notation, both the {}, and the .format() instruction itself, are represented by a simple %.

>>> 'PI = %.5f to 5 decimal places' % 3.14159265
'PI = 3.14159 to 5 decimal places'
Python

It is planned to deprecate the use of % for formatting purposes (sometimes called “printf-style formatting”) at some stage in Python 3, so caution should be taken when using %-style formatting in new code. However, this syntax appears in a lot of existing Python code and it is helpful to understand what it does.

Of course, any string that you create using the above formatting techniques can be printed to the screen using the the print() function.

 
© 2025  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Access Statement
CVW material development is supported by NSF OAC awards 1854828, 2321040, 2323116 (UT Austin) and 2005506 (Indiana University)