Python format() Function: No-BS Guide by Example

5/5 - (4 votes)
Python format() Function: No-BS Guide by Example

The web is filled with shitty tutorials about Python’s formatting feature. At times, it can become really confusing—and it’s hard to see the forest for the trees. In this tutorial, I’ll try to gradually build a basic understanding of the built-in format() function, what it does, and how you can use it to become a more effective coder.

So, let’s start with the most elementary question:

What is the format() function and why should you care?

If you’re a data scientist, you know that the format of the data is a critical preprocessing step. Here are some examples where formatting is required:

  • You read dates from a file with the format '11/9/2021' and you want them to have the format '11/09/2021'.
  • You read house prices from a database and they come in the format '1,000,000$'—and what you want is: '$1,000,000'.
  • You need to construct a string from multiple integer variables but you don’t like string concatenation 'House' + str(num) + ' price is ' + str(price) + ' USD'—just to obtain 'House 2 price is 10000 USD'.

The format() function provides you a powerful tool to solve all those challenges easily. In fact, if you’ve mastered the format() function, you’ll see that you can apply it to more and more every-day problems.

After all, programmers write programs that transform an input to an output—that’s all there is.

Python’s built-in format(value, spec) function transforms input of one format into output of another format defined by you. Specifically, it applies the format specifier spec to the argument value and returns a formatted representation of value. For example, format(42, 'f') returns the string representation '42.000000'.

ArgumentvalueThe value to be formatted. Can be a string or an integer or any other object implementing the __format__() method.
ArgumentspecThe formatting specifier to control how value should be formatted. Uses the Format Specification Mini-Language.
Return ValuestringReturns the formatted representation of value.

Learn format() By Example

Now—all of this information is very abstract and it probably doesn’t mean much to you. Let’s dive into the formatting functionality one example at a time.

format() Integer

The most basic use of the format function is to pass an integer value into it:

>>> format(42)

The format function behaves just like the built-in str() function that converts the integer to a string. You can already extract the first two pieces of knowledge from this example:

Insight: The output of the format() function is always a string value.

Insight: The first argument of the format() function is the value to be formatted.

Did you absorb both insights?

format() to Convert Int to Float

Great, let’s make it a bit more useful: you want to convert the integer value 42 to a float value 42.0. Can you do it with the format() function? Sure!

>>> format(42, 'f')

You pass the second optional argument 'f' that is called the format specifier. There’s a whole format specifier language that allows you to do all kinds of powerful transformations of your input value. The 'f' format specifier simply stands for the formatting objective 'float'.

Insight: The second argument of format() is the format specifier.

format() Precision Specifier

You find that the many trailing zeros in '42.000000' do not look pretty and are too precise for your purposes. So, how to reduce the precision?

By adding a precision prefix to the format specifier with .p whereas p is the precision, i.e., the number of zeros after the decimal point for a floating point number.

>>> format(42, '.10f')
>>> format(42, '.2f')

This looks prettier! And, it leads us the next insight!

Insight: The .p prefix in the format specifier controls the precision of floating point numbers.

format() Important Type Specifiers

There are many basic format specifiers such as 'f'. Here’s a table of the most important ones—with examples:

'b'>>> format(42, 'b')

Binary format. Outputs the number in base 2.
'd'>>> format(0b101010, 'd')
Decimal Integer format. Given a number in another base (e.g., binary). Formats the number into base 10.
'e'>>> format(1000, '.2e')
>>> format(1000, '.0e')
Scientific exponent format. For a given precision p, formats the number in scientific notation with the letter 'e' separating the coefficient from the exponent.
'f'>>> format(42, '.10f')
>>> format(42, '.2f')
Float fixed-point format. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point. Per default, six positions after the decimal point.

These are the most important basic format specifiers. For a full list, please visit the official documentation. Otherwise, stay with me to learn about more usages of the format function!

format() Width Specifier

Say, you require that your formatted output has a specific width. For example, all strings printed to the shell should have a width of 25 positions. Can you do this with format()? You guessed it: yes!

>>> format(42, '25f')
'                42.000000'
>>> format(42, '15f')
'      42.000000'

To define the width of the output, add the number of digits as a prefix to the format specifier—in the previous examples 25 digits and 15 digits, respectively.

format() Combining Specifiers

You can also combine it with the precision specifier like so:

>>> format(42, '15.2f')
'          42.00'
  • The integer number 15 defines the width,
  • The precision specifier .2 defines the number of decimal points, and
  • The character 'f' controls the output type (float).

Insight: You can combine multiple specifiers to fine-tune your output format.

So, let’s use this to nicely align floats in your Python shell output:

floats = [1.0,

for f in floats:

And using the format specifier to prettify the output:

floats = [1.0,

for f in floats:
    print(format(f, '25.2f'))


Now, the numbers are nicely aligned, and all of them have the same number of digits after the floating point.

Format Specification Language General Form

You’ve seen many different examples of the format specifier. But, formally, how does it work and how can you combine all of those bits and pieces?

Here’s the formal language syntax of the format() specifier from the official documentation:

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

I know it’s very hard to grasp the meaning of this language—but stay with me for a moment! First of all, you need to know that everything in between the square brackets [...] is an optional language element. You start with format_spec and replace it subsequently with the optional language elements to obtain your final format specifier.

format() Function Example Explanation

For example, you can have a fill character, followed by the align element, followed by the width, followed by the type:

format_spec -->
fill align width type -->
<any character> "<" | ">" | "=" | "^" digit+ "b"| ... | "%" -->
>>> format(42, 'x=15f')
  • fill is replaced with x to fill all positions with the character 'x'.
  • align is replaced with = to align the string at the center rather than on the right or left.
  • width is replaced with 15 to make the whole string output 15 positions wide.
  • type is replaced with ‘f’ to convert the int 42 to the float 42.000000.

format() vs string.format() vs __format__()

The built-in format(value, spec) function is similar to the string.format(spec) method—both internally call the value.__format__() method. However, the format() function also applies to non-string values.

Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link:

Want to keep improving your Python skills? Check out our free Python cheat sheets:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!