How to Handle Placeholders in Python's Format Method
The format() method lets you create a template for displaying text.
Example
string = "My name is {0} and I live in {1}".format("Andrea", "Rome")
This will result in the string:
'My name is Andrea and I live in Rome'
So far, so good. The method is useful, but nothing special yet.
However, the format method has a lot of potential because you can apply different formatting to each placeholder.
Working with Placeholders
To format a placeholder, you add a colon after the parameter name.
To the right of the colon, you can include various formatting options.
:> right alignment
:< left alignment
:* fill with spaces
:5.3f format as a real number
:c character
:n format as a locale-specific number
:b binary value
:d decimal value
:o octal value
:x hexadecimal value
:X uppercase hexadecimal value
Practical Examples
Example 1
string = "The number {0:d} in binary is {0:b}".format(5)
The resulting string is:
'The number 5 in binary is 101'
Example 2
You can format real numbers with a custom template.
string = "The total cost is {0:*10.3f}".format(1234.56789)
The result is:
'The total cost is 1234.568'
Example 3
You can also align text to the right or left, filling in the empty spaces with a character of your choice.
string = "The total cost is {0:*>10.3f}".format(1234.56789)
The result is:
'The total cost is **1234.568'