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
- You read house prices from a database and they come in the format
'1,000,000$'—and what you want is:
- 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'.
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.
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
|Argument||The value to be formatted. Can be a string or an integer or any other object implementing the |
|Argument||The formatting specifier to control how value should be formatted. Uses the Format Specification Mini-Language.|
|Return Value||Returns the formatted representation of |
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.
The most basic use of the format function is to pass an integer value into it:
>>> format(42) '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') '42.000000'
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
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 is the precision, i.e., the number of zeros after the decimal point for a floating point number.
>>> format(42, '.10f') '42.0000000000' >>> format(42, '.2f') '42.00'
This looks prettier! And, it leads us the next insight!
.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:
|Binary format. Outputs the number in base 2.|
|Decimal Integer format. Given a number in another base (e.g., binary). Formats the number into base 10.|
|Scientific exponent format. For a given precision |
|Float fixed-point format. For a given precision |
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
15defines the width,
- The precision specifier
.2defines 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:
# BEFORE floats = [1.0, 3.14, 4.666, 424242.424242] for f in floats: print(f) ''' 1.0 3.14 4.666 424242.424242 '''
And using the format specifier to prettify the output:
# AFTER floats = [1.0, 3.14, 4.666, 424242.424242] for f in floats: print(format(f, '25.2f')) ''' 1.00 3.14 4.67 424242.42 '''
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 ::= [[
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.
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"| ... | "%" --> x=15f
>>> format(42, 'x=15f') 'xxxxxx42.000000'
fillis replaced with
xto fill all positions with the character
alignis replaced with
=to align the string at the center rather than on the right or left.
widthis replaced with
15to make the whole string output 15 positions wide.
typeis replaced with ‘f’ to convert the int
42to the float
format() vs string.format() vs __format__()
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.
But before we move on, I’m excited to present you my brand-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).
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!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.