The print function in Python is a very commonly used function that can be used to output information. andprint(f) is a new formatted output method added after Python 3.6
, also known as f-string.
In Python, print(f'') is the syntax for formatting strings (f-string), which allows you to embed expressions in strings that are replaced by their values at runtime. The f or F prefix means that this is a formatted string literal.
Inside the braces {} in f’’ or F’’, you can put any valid Python expression. When the print function is executed, these expressions are evaluated and the result is inserted into the corresponding position of the string.
If you want to know more, please refer toOfficial Documentation
1. What is f-string?
In Python 3.6, a new formatted string output (f-string) is added, that is, the string is preceded by the letter f. Use f-string to insert variable values into strings, and the expression syntax is obvious and intuitive.
2. Basic usage of f-string
The basic format of f-string is:
f'string {expression} string'
Among them: In the braces are expressions, and the value of the expression will be inserted into the string.
Here is a simple example:
name = "Alice" print(f"Hello, {name}!") # Output: Hello, Alice! x = 5 y = 10 print(f"The sum of {x} and {y} is {x + y}.") # Output: The sum of 5 and 10 is 15.
In the example above, enclose the variable in curly braces and then prefix the braces with the letter f. In this way, when a variable is referenced with {} in a string, the variable will be automatically parsed.
Comparison of three formatting characters
name = 'tom' age = '18' # Method 1:print(f'I am{name},This year{age}age。') # Method 2:print('I am{},This year{}age。'.format(name, age)) # Method 3:print('I am %s, this year %s' % (name, age))
3. Basic usage examples
Example 1: Basic usage
name = "Alice" print(f"Hello, {name}!") # Output: Hello, Alice!
Example 2: Arithmetic operation
x = 5 y = 10 print(f"The sum of {x} and {y} is {x + y}.") # Output: The sum of 5 and 10 is 15.
Example 3: Accessing dictionary elements
person = {"name": "Bob", "age": 30} print(f"{person['name']} is {person['age']} years old.") # Output: Bob is 30 years old.
Example 4: Using functions
def square(x): return x ** 2 number = 4 print(f"The square of {number} is {square(number)}.") # Output: The square of 4 is 16.
Example 5: Format numbers (usually used to retain the decimal places of floating point numbers.)
pi = 3.141592653589793 print(f"The value of pi is approximately {pi:.2f}.") # Output: The value of pi is approximately 3.14.
In the last example above, :.2f is a format specifier that tells Python to format the floating point number pi as a string with two decimals.
4. Advanced usage of f-string
4.1. Alignment
The {} of f-string uses content:format to set the string format. If you want to use the default format, you do not have to specify :format. Support left-alignment, right-alignment, and center-alignment.
If you want to print variables to a specific location, you can use alignment
4.1.1. By default, use spaces to fill
name = 'ready' print(f'|{name:>20}|') # Right-aligned, fill the string length to 20# | ready| print(f'{name:<20}') # Left aligned, fill the string length to 20# |ready | print(f'{name:^20}') # Align in the center, fill the string length to 20# | ready |
Notice the number:n in the first print. Here n means the width of the variable number (including the width of the number itself) starting from "|", and you can also choose to be left-aligned, center-aligned, or right-aligned.
In name:>20, the print result takes up 20 characters in total, the string is printed on the right, and the left side is filled with spaces.
In name:^20, the print result takes up 20 characters in total and the string is in the middle.
4.1.2. Use other characters to fill
name = 'ready' print(f'{name:a>20}') # aaaaaaaaaaaaaaaready print(f'{name:1<20}') # ready111111111111111 print(f'{name:-^20}') # --------ready-------
4.2. Debugging mode
The debugging mode of f-string is used{variable = }
replacevariable = {}
, as shown in the following code.
In debugging of f-string, math operations can also be performed, as seen in the example below.
x = 10 y = 20 print(f"x = {x}, y = {y}") # Original method# x = 10, y = 20 print(f"{x = }, {y = }") # Debug mode# x = 10, y = 20 # Compute the value of x*yprint(f"{x * y = }") # x * y = 200 print(f"{x = :.3f}") # x = 10.000
You can see that using debug mode reduces the amount of code, and the output content is consistent.
This feature is called "debug" and can be used in conjunction with other modifiers.It also retains spaces
, so f"{x=}" and f"{x=}" will produce different strings.
4.3. Variable name formatting
Sometimes, we need to use variable names in strings instead of variable values, which can be used!r
or!s
。
For example, the following example:
name = "Tom" print(f"His name is {name!r}.") #Output:His name is'Tom'
In the above example, the value of the variable name is Tom, but after using !r, the output is 'Tom', that is, the value of the string type
4.4. Expression formatting
f-string supports the use of expressions in curly braces, thus handling some complex logic.
For example, the following example:
name ="Tom" age=20 print(f"{'He' if age<18 else 'She'} is {name}.")#Output:She is Tom.
In the above example, the if statement is used to implement the judgment output based on age and gender.
4.5. Format numbers
Various formatting/converting can be done with numbers, and here are some examples:
- Set the number of decimal places (precision): Use:.nf, where n is the number of decimal places
- Hexadecimal conversion
- Binary conversion
- Octal conversion
- Scientific Counting Method
- Fill the number with leading zeros: Use:0n, where n is the total number of characters
number = 420 # decimal places # Set the accuracyprint(f"number: {number:.2f}") # hex conversion # Hexadecimal conversionprint(f"hex: {number:#0x}") # binary conversion # Binary conversionprint(f"binary: {number:b}") # octal conversion # Octal conversionprint(f"octal: {number:o}") # scientific notation # Scientific Counting Methodprint(f"scientific: {number:e}") # total number of characters # Fill in leading 0print(f"Number: {number:09}")
Output
number: 420.00
hex: 0x1a4
binary: 110100100
octal: 644
scientific: 4.200000e+02
Number: 000000420
Type conversion identifiers include: d integer, f floating point number, g Select %f or %e and s strings according to the size of the value.
Thousand separator, percentage
a = 1000000 print(f"{a= :,}") # a= 1,000,000 per = 0.59596 print(f"{per = :.2%}") # per = 59.60%
:.2%
Tell Python to set 2 decimal places and add a percent sign at the end of the string.
4.6. Date formatting
If you want to format a date, you can create an example date time value. Just like formatting dates in an application, you can define the format you want in f-string, for example: <date_format>
The following formats a UTC datetime as:
- No microseconds
- Date only
- Time only
- Take the morning/afternoon time
- 24-hour format
import datetime today = () print(f"datetime : {today}") # datetime : 2024-02-28 06:11:04.848944 print(f"date time: {today:%m/%d/%Y %H:%M:%S}") # No microseconds# date time: 02/28/2024 06:11:04 print(f"date: {today:%m/%d/%Y}") # Date only# date: 02/28/2024 print(f"time: {today:%H:%M:%S.%f}") # Time only# time: 06:11:04.848944 print(f"time: {today:%H:%M:%S %p}") # Time to bring morning/afternoon# time: 06:11:04 AM print(f"time: {today:%H:%M}") # 24-hour time# time: 06:11
You can also do more with the formatting option, here is how to get the day of the week and the day of the year from the date, and also calculate how many days of the year have passed.
print(f"locale appropriate: {today:%c}") # Local appropriate date and time representation# locale appropriate: Wed Feb 28 06:13:35 2024 print(f"weekday: {today:%A}") # Get the current date is the day of the week# weekday: Wednesday print(f"day of year: {today:%j}") # Get what day of the year the current date is# day of year: 059 day_of_year = f"{today:%j}" print(f"progress % year: {int(day_of_year)/365 * 100:.2f}%")# Get the elapsed time of the year (percentage)# progress % year: 16.16%
4.7. Quotation mark specifications and escape issues
1. The quotes used in {} in f-string cannot conflict with the quote delimiter outside {}, that is, the following operations are not allowed:
print(f'My name is {'Li Hua'}') # SyntaxError: f-string: expecting '}'
Change to any of the following forms to output normally (the following lists all possible cases):
"""The external delimiter is single quotes""" print(f'My name is {"Li Hua"}') print(f'My name is {"""Li Hua"""}') """The external delimiter is double quotes""" print(f"My name is {'Li Hua'}") print(f"My name is {'''Li Hua'''}") """The external delimiter is double three quotes""" print(f"""My name is {'Li Hua'}""") print(f"""My name is {"Li Hua"}""") print(f"""My name is {'''Li Hua'''}""") """The external delimiter is single three quotes""" print(f'''My name is {'Li Hua'}''') print(f'''My name is {"Li Hua"}''') print(f'''My name is {"""Li Hua"""}''')
Summary: If multiple quotes may appear inside the string but do not want to worry about the quotes, use the external delimiter directly."""
Just do it.
2. Quotations outside braces can also be used \escaped, but \escaped in braces cannot be used
print(f'I\'m{"Little Yang"}') # Output: I'm Xiao Yangprint(f'I\'m{"Little Yang"},{I\'m OK}') #Output''' print(f'I\'m{"Little Yang"},{I\'m OK}') ^ SyntaxError: f-string expression part cannot include a backslash '''
If you do need to use escape in {}, the content containing \ should be declared separately as a variable
s = '\'' print(f"{s}") # '
4.8. Problems in the use of curly braces in f-string
If you need to display braces outside f-string braces, two braces {{ }} can be displayed; quotes are required in braces, and quotes are used (the rules are as described in Article 7).
print(f"Recommend a book for everyone{{Species Origin}}") #Output:Recommend a book for everyone{Species Origin}
This is the introduction to this article about the basic usage of f-string in python. For more related python f-string content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!