String Formatting
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'.
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.
Alternatively, we can assign keywords to the positional variables. The corresponding inputs ('Joe' and 'Hello', in this case) are substituted accordingly.
Arguments that are of a numerical type will automatically be converted into strings.
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.
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 %.
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.