1. Basic usage
name = "Alice" age = 25 # Embed variables using f-string message = f"My name is {name} and I am {age} years old." print(message) # Output My name is Alice and I am 25 years old.
2. Embed expressions
a = 5 b = 10 # Embed expressions using f-string result = f"The sum of {a} and {b} is {a + b}." print(result) # Output The sum of 5 and 10 is 15.
3. Format output
1. Digital formatting
1.1 Floating point number formatting
grammar:{value:.nf}
,inn
is the number of decimal places reserved.
pi = 3.141592653589793 # Keep two decimal places formatted_pi = f"Pi rounded to 2 decimal places: {pi:.2f}" print(formatted_pi) #Output Pi rounded to 2 decimal places: 3.14
1.2 Integer Zero Complement
grammar:{value:0nd}
,inn
It is the total number of digits, and the insufficient part is used0
Fill.
number = 42 # Add zero to 5 digits formatted_number = f"The number is {number:05d}" print(formatted_number) #Output The number is 00042
1.3 thousand separator
grammar:{value:,}
, use commas to separate thousands of digits.
population = 1234567890 # Add a thousand separator formatted_population = f"The world population is {population:,}" print(formatted_population) #Output The world population is 1,234,567,890
1.4 percent formatting
grammar:{value:.n%}
,inn
is the number of decimal places reserved.
ratio = 0.4567 # Format as a percentage, retain two decimal places formatted_ratio = f"The ratio is {ratio:.2%}" print(formatted_ratio) #Output The ratio is 45.67%
2. String formatting
2.1 Alignment and fill
grammar:{value:width}
or{value:<width}
、{value:>width}
、{value:^width}
,inwidth
It is the total width.
-
<
: Left aligned -
>
: Right aligned -
^
: Center-aligned
name = "Alice" # Align left, total width is 10, fill with ' ' formatted_name = f"Name: {name:<10}!" print(formatted_name) # Right-aligned, total width is 10, fill with '*' formatted_name = f"Name: {name:*>10}!" print(formatted_name) # Align in the center, with a total width of 10, fill with '=' formatted_name = f"Name: {name:=^10}!" print(formatted_name) #Output Name: Alice ! Name: *****Alice! Name: ==Alice===!
2.2 Truncate string
grammar:{value:.n}
,inn
is the number of characters reserved.
long_text = "This is a very long string." # Cut to the first 10 characters formatted_text = f"Truncated: {long_text:.10}" print(formatted_text) #Output Truncated: This is a
3. Date and time format
3.1 Format date
usestrftime
Combination of methodsf-string
Format date.
from datetime import datetime now = () # Format date formatted_date = f"Today is {now:%Y-%m-%d}" print(formatted_date) #Output Today is 2023-10-05
3.2 Format time
from datetime import datetime now = () # Format time formatted_time = f"The time is {now:%H:%M:%S}" print(formatted_time) #Output The time is 14:35:22
4. Other formatting
4.1 Scientific Counting Method
grammar:{value:.ne}
,inn
is the number of decimal places reserved.
number = 1234567890 # Scientific notation method, retaining two decimal places formatted_number = f"Scientific notation: {number:.2e}" print(formatted_number) #Output Scientific notation: 1.23e+09
4.2 Binary, octal, hexadecimal
grammar:
- Binary:
{value:b}
- Octal:
{value:o}
- hexadecimal:
{value:x}
(lower case) or{value:X}
(capital)
number = 255 # Binary binary = f"Binary: {number:b}" print(binary) # octal octal = f"Octal: {number:o}" print(octal) # hexadecimal hexadecimal = f"Hexadecimal: {number:x}" print(hexadecimal) #Output Binary: 11111111 Octal: 377 Hexadecimal: ff
4. Call functions and methods
name = "alice" # Call the title() method of the string formatted_name = f"Hello, {()}!" print(formatted_name) # Output Hello, Alice!
String title method:
Include the initial letters of all words like 's in it's
Difference from capitalize(): capitalize() only capitalizes the first letter of the first word of the entire string and the rest are lowercase.
5. Use dictionaries and lists
person = {"name": "Bob", "age": 30} # Access values in the dictionary info = f"{person['name']} is {person['age']} years old." print(info) numbers = [1, 2, 3, 4, 5] # Access elements in the list summary = f"The first number is {numbers[0]} and the last number is {numbers[-1]}." print(summary) #Output Bob is 30 years old. The first number is 1 and the last number is 5.
6. Multi-line f-string
name = "Charlie" age = 35 # Multi-line f-string message = f""" Name: {name} Age: {age} """ print(message) #Output Name: Charlie Age: 35
7. Nested f-string
a = 5 b = 10 #Nested f-string result = f"The sum of {a} and {b} is {f'{a + b}'}." print(result) # Output The sum of 5 and 10 is 15.
This is the end of this article about the use of f-string string formatting in Python. For more related content on Python f-string string formatting, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!