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'

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python

  1. The Python Language
  2. How to Install Python on Your PC
  3. How to Write a Program in Python
  4. How to Use Python in Interactive Mode
  5. Variables
  6. Numbers
  7. Logical Operators
  8. Iterative Structures (or Loops)
  9. Conditional Structures
  10. Exceptions
  11. Files in Python
  12. Classes
  13. Modules

Miscellaneous

Source