15 Things I Regret Not Knowing Earlier About Python Formatted Strings
1) {var=}
If we add a = sign after a variable, it prints both variable name and value.
Which is useful for debugging and logging purposes.
2) Rounding to N decimal places
To round a number to 2 decimal places, we can use {number:.2f}
To round a number to 3 decimal places, we can use {number:.3f}
3) Rounding to N significant figures
To round a number to 2 significant figures, we can use {number:.2g}
To round a number to 3 significant figures, we can use {number:.3g}
4) Formatted raw strings
A raw string is a string where \ is a literal backslash — a string where \ no longer escapes other characters.
To make a string a formatted string, we add a f in front of it.
To make a string a raw string, we add a r in front of it.
To make a string that is both a formatted string and a raw string, we add either a fr or rf in front of our string. Both works.
5) Alignment with whitespace
There are 3 ways to pad a variable with spaces to a width of 20 characters:
{ var:<20 } aligns the variable var to the left
{ var:>20 } aligns the variable var to the right
{ var:^20 } aligns the variable var to the center
Note — this breaks if var has a length than is greater than 20
Quick Pause
I recently wrote a book — 101 Things I Never Knew About Python
Check it out here if you wish to support me as a writer!
Link: https://payhip.com/b/vywcf
6) Alignment with other characters
We don’t necessarily have to do the above with whitespace. We can specify other characters if we want to.
To do this, we simply need to add the desired character right after the colon.
7) Quotes within quotes in f-strings
This used to be illegal in an older version of Python, but has become legal now in recent versions — I’m using Python 3.12
If our variables inside our f-string require quotes, we can simply use them as they are.
in the past: we’ll get a syntax error
now: this works perfectly fine
8) Inserting commas into large numbers
We can insert commas into very large numbers to make it easier to read. By default, every 3 digits will be grouped together.
We can do this by simply using { number:, }
9) Displaying raw output
Adding a !r after a variable in an f-string allows us to display raw output.
Which is equivalent to displaying repr(variable).
Raw outputs are usually used for debugging and logging, and this shortbut might come in useful here in these use cases.
10) Formatting datetime
We can also format datetime objects directly in f-strings.
A simple example below:
%Y represents the year in full eg. 2024
%y represents the year but truncated eg. 24
%m represents the month as a number
%d represents the day as a number
%A represents the day of the week eg. Monday, Tuesday
More datetime format codes can be found here: https://docs.python.org/3/library/datetime.html#format-codes
11) Numbers to percentage
We can convert numbers directly to percentages in f-strings too.
In addition, we can specify how many decimal places there should be.
12) Binary, octal & hexadecimal numbers
We can represent numbers as binary, octal and hexadecimal numbers in f-strings.
to represents numbers as binary (base 2), we add a :b after it
to represents numbers as octal (base 8), we add a :o after it
to represents numbers as hexadecimal (base 16), we add a :x after it
13) Triple quoted f-strings
Triple-quoted strings span multiple lines, and treat newlines as actual newline characters.
We can simply turn a triple-quoted string into a formatted triple quoted string by adding a f in front of it.
14) .format() with positional arguments
One limitation of f-strings is that we cannot use it as a template string that can be stored in a database.
To be able to store such a template string in a database for multiple uses, we might need to do something like this:
Note that the first argument name is assigned to the first empty bracket, while the second argument age is assigned to the second empty bracket.
15) .format() with keyword arguments
One limitation of using .format() with positional arguments is that our arguments must strictly follow a certain order.
To overcome this limitation, we can use keyword arguments instead. The catch is that we need to now add our variable names into our strings, like this:
We can switch the order of the keyword arguments and it’ll still work
Conclusion
Hope you learnt at least a couple new things about Python formatted strings today.
Cheers,
Liu