Python f-string: format, float, precision, 0 padding, new line,, error, binary, hex,
F-string, which stands for Formatted string, is the most intuitive way to manipulate strings and work with formatting teams in Python, and is a new feature introduced in 3.6
.
In this article, we'll cover the basics of using F-strings, along with topics such as formatting decimal places, line breaks, for statements, and error handling.
1. How to Use F-Strings in Python
Here's how F-strings have changed Python.
When given the following two variables,
name = "Jonn Doe"
age = 30
If you want to get the following output
My name is John Doe. I'm 30 years old this year.
Using Python's default string method, I could have used three different methods, as shown below.
str1 = "My name is " + name + ". I'm " + str(age) + " years old this year."
str2 = "My name is %s. I'm %d years old this year." % (name, age)
str3 = "My name is {}. I'm {} years old this year.".format(name, age)
# Output:
# My name is Jonn Doe. I'm 30 years old this year.
F-strings allow you to write the most readable code, like this
f_str1 = f"My name is {name}. I'm {age} years old this year."
# Output:
# My name is Jonn Doe. I'm 30 years old this year.
As you can see in the example, f
precedes the quotes that define the string literal, and the value of the variable you're inserting is enclosed in curly braces {}
.
Inside the braces, you can also insert an expression, as shown below, or a container type such as a list.
friends = ["Mark", "Elon"]
f_str2 = f"My name is {name}. I'm {age + 1 } years old next year. My friends are {friends}."
# Output:
# My name is Jonn Doe. I'm 31 years old next year. My friends are ['Mark', 'Elon'].
This ability to insert variables between strings for output is called string interpolation, and is supported by most modern programming languages.
F-strings are Python's way of supporting string interpolation.
Now that we've covered the basics of using F-strings, let's move on to the most frequently asked questions.
2. Precision float point
F-strings have a simple symbol called a format specifier, which allows you to format the output string however you like. This is especially useful for representing numbers. In this section, we'll look at decimal representation, one of several ways to represent numbers.
F-strings give you the ability to unify a small number of digits of different lengths, and then output them nicely.
It's easy to use.
If you add :.2f
after a variable in curly braces, you'll just output the number you entered.
In our case, we've entered 2
, so we'll print up to two decimal places.
float1 = 11.38471
float2 = 8.1
print(f'float1: {float1:.2f}, float2: {float2:.2f}')
# Output:
# float1: 11.38, float2: 8.10
The result,
We've added 0
to the end of float1
because it has more than two decimal places, and float2
because it ends in the first position.
If it's a very small prime number, it can also be formatted with the floating point character e
.
By adding :e
, Python tells you how many digits to the right of the decimal point. You can also specify the number of digits.
Let's check it out with an example.
too_small_num = 0.00000000123
print(f'too_small_num: {too_small_num:e}, too_samll_num_3: {too_small_num:.3e}')
# Output:
# too_small_num: 1.230000e-09, too_samll_num_3: 1.230e-09
Finally, you can also output percentages (%) as decimals, and again, you can set the number of decimal places.
score = 0.95
print(f'score(%): {score:.0%}, {score:.2%}, {score:.4%}')
# Output:
# score(%): 95%, 95.00%, 95.0000%
3. Python f-string digits
We already learned a lot about setting decimal places in Section 2. The same principles can be applied to integer numbers.
If decimals were .0f
, floats were .0e
, and percentages were .0%
, then integers are ,d
.
Comma, not underscore.
Useful for readable output of large numbers above 1,000
.
big_num = 10000020003
print(f'big_num_with_comma: {big_num:,d}')
# Output:
# big_num_with_comma: 10,000,020,003
You can also add spaces with ^
, and output binary, octal, and hexadecimal numbers.
Check it out in code.
number = 25
point = 2.543
print(f"Binary: {number:b}")
print(f"Integer: {number:d}")
print(f"octal:{number:o}")
print(f"Hexadecimal: {number:x}")
print(f"Floating point: {point:.2e}")
print(f"Decimal: {point:.2f}")
print(f"Decimal or floating point automatically: {point:.2g}")
print(f"Percent: {point:.2%}")
# Output:
# Binary: 11001
# Integer: 25
# octal: 31
# Hexadecimal: 19
# Floating point: 2.54e+00
# Decimal: 2.54
# Decimal or floating point automatically: 2.5
# Percent: 254.30
4. New Line
Python supports multiline strings ('''
), which can be wrapped intuitively.
To use wrapping in any other way, you must use the symbol \n
, where n
means newline.
multiline1 = '''multiline
string'''
multiline2 = f'multiline\nstring'
# Output:
# multiline
# string
In fact, multiline strings using '''
are just a convenience syntax that automatically inserts \n
.
5. f-string with for loop
F-strings can also be used in conjunction with a for statement to write more readable code. The following code prints the names of friends in a list one at a time.
friends = ["Mark", "Elon"]
for friend in friends:
print(f"My friend {friend}")
# Output:
# My friend Mark
# My friend Elon
6. Troubleshooting Python f-string errors
Here are some common errors you may encounter when using f-strings. We summarize the causes and solutions for each one.
-
SyntaxError: Invalid syntax:
. Occurs when you don't follow the f-string syntax. Make sure you're prefixing string literals withf
and enclosing variables or expressions in braces{}
correctly. -
NameError: Name '...' is not defined:
. This error occurs if you are using an undeclared variable. Please make sure you have declared the variables you have inserted between the strings. -
TypeError: '...' object is not callable:
This error occurs when you insert a variable or expression in the F-string syntax without clearly typing the curly braces{}
. Please check that you are using the correct format. Instead, calculate the result first and then embed it in the f-string. -
SyntaxError: f-string expression part cannot contain a backslash:
. In all Python strings except raw strings, the backslash\
has a special meaning. This is because it is used to indicate line breaks, tabs, etc. with symbols like\n \t
. So using a backslash directly in a variable or expression will result in an error.
If you must use a backslash, use it with another backslash that escapes to return to a normal string.
print(f'\\')
# Output:
# \
ValueError: Single '}' encountered in format string:
This error occurs when you type an extra curly brace, likeprint(f'{{name}')
. Fix any typos, and if you want to use braces, escape them, like{{
or}}
.
print(f'{{{name}}}')
# Output:
# {John Doe}
7. Conclusion
So far, we've talked about several topics related to F-strings in Python. No matter what domain you develop in, F-strings are probably one of the features you encounter every day. I hope this helps you become familiar with them and use them when the time is right.
