SoFunction
Updated on 2025-05-22

Python f-string implements efficient string formatting

f-string, called formatted string constants, is a new string formatting method introduced in Python 3.6. This method originated from PEP 498 - Literal String Interpolation, and its main purpose is to make formatted strings easier.

There are 3 commonly used methods for formatting strings in python:

  • Placeholder For example print("my name is " % "hanmeimei")
  • format For example print("my name is {}".format("hanmeimei"))
  • f-string For example print(f"my name is {'hanmeimei'}")

Among them, f-string is the clearest and most efficient method recommended. This article mainly explains the common usage methods of f-string.

1. Syntax

f-string uses content:format} to set the string format, where content is the content that replaces and fills in the string, which can be variables, expressions, functions, etc. format is a format descriptor, which can be omitted.

The complete format description of Python f-string formatted strings is implemented through the format specification after the colon (:). This formatting specification can be used to control the output format of data types such as numbers, strings, time and date. Here is a complete formatting description, including common formatting options and their usage.

f"{expression:{flags}{width}{precision}{type}}"
  • expression: The value to format (such as numbers, strings, etc.).
  • flags: Used to specify fill method, alignment method, etc.
  • width: The minimum width of the output. If the output value width is less than the specified width, fill is performed.
  • precision: Used to control the decimal point accuracy or other numerical accuracy of floating points.
  • type: Used to specify format types, such as floating points, integers, strings, etc.

Simple use

f-string uses braces {} to represent the replaced field, and directly fill in the replacement content:

>>> name = 'Eric'
>>> f'Hello, my name is {name}'
'Hello, my name is Eric'

>>> number = 7
>>> f'My lucky number is {number}'
'My lucky number is 7'

>>> price = 19.99
>>> f'The price of this book is {price}'
'The price of this book is 19.99'

Note: No matter what the type of the variable is, you will get the result of the string type in the end.

2. How to use

2.1 Width control

The most common thing about using f-string is to control variable accuracy and output width

Format descriptor Meaning and function
width integer width Specifies the width 0width: integer width specifies the width, the beginning of 0 specifies the high position to fill the width with 0
Integer width specifies width, integer precision specifies display accuracy

The dot is divided, the output width is controlled before the dot, and the output accuracy is controlled after the origin.

Controls the output width, whether it is a numeric type or a string type. Syntax: f"{variable: width}"

  • Specify width is less than variable width: Normal output
  • Specify width greater than variable width: Output the specified width, complete with spaces. Fill the string right, fill the value left
>>> a = 3.1415926
# Variable width 9, specified width 20, value left complement>>> print(f"{a:20}")
           3.1415926
>>> print(len(f"{a:20}"))
20


>>> c = "hello world"

>>> print(f"{c:5}")
hello world

>>> print(f"{c:25}")
hello world          

# The variable has only 11 strings, the specified width is 25, the output length is 25, and the space is filled>>> print(len(f"{c:25}"))
25

There is a special use of f "{variable: 0 width}". Adding 0 before the width can achieve the completion of variable display with 0 before the variable display.

>>> a = 3.1415926

>>> print(f"{a:020}")
000000000003.1415926
>>> 

2.2 Accuracy control

Value

Integers and floating-point numbers use f-string to control the accuracy of the output. The syntax is f"{variable: .4f}", where 4f refers to the number of digits after the decimal point, which can achieve precision truncation or expansion. The rule of truncation is rounding, and expansion is to increase the accuracy to the specified number of digits.

>>> a = 3.1415926

>>> print(f"{a:.4f}")
3.1416

>>> b = 100

>>> print(f"{b}")
'100'

>>> print(f"{b:.6f}")
'100.000000'
>>> 

String

Strings can also control the output accuracy, using the syntax ** f"{variable:.4s}"**, where 4s refers to the length of the string, s can be omitted, and truncation can be achieved, but will not be filled. The length set is greater than the variable length, and the output is still the variable length.

>>> c = "hello world"

>>> print(f"{c:.2}")
he

>>> print(f"{c:.10s}")
hello worl
    
>>> print(f"{c:.5s}")
hello

# Accuracy exceeds length will not be filled>>> print(f"{c:.20s}")
hello world

>>> print(len(f"{c:.20s}"))
11

Width and precision can be controlled simultaneously

>>> a = 3.1415926
>>> print(f"{a:14.4f}")
        3.1416

>>> c = "hello world"
>>> print(f"{c:25.4s}")
hell 

2.3 Alignment

Alignment refers to how to display when the specified width is greater than the variable width when the output is displayed. The options include:

  • >: Right aligned
  • <: Left alignment (default behavior)
  • ^: Align center
&gt;&gt;&gt; c = "hello world"

# After setting the width, space fill will appear. The string is right-filled, that is, left-aligned.&gt;&gt;&gt; print(f"{c:20}")
hello world         

&gt;&gt;&gt; print(len(f"{c:20}"))
20

&gt;&gt;&gt; print(f"{c:&lt;20}")
hello world         
&gt;&gt;&gt; 

&gt;&gt;&gt; print(f"{c:&gt;20}")
         hello world

&gt;&gt;&gt; print(f"{c:^20}")
    hello world     

2.4 Fill

When aligning, use spaces to fill by default, or with specified characters. Use syntax **f"{variable: fill character <width}" **, fill characters are common: -, +, *, 0, etc.

>>> c = "hello world"

>>> print(f"{c:<20}")
hello world         

>>> print(f"{c:-<20}")
hello world---------

>>> print(f"{c:->20}")
---------hello world
>>> 
>>> print(f"{c:-^20}")
----hello world-----

>>> print(f"{c:*^20}")
****hello world*****

>>> print(f"{c:0^20}")
0000hello world00000

2.5 Data format

Type Identifier (type) A type identifier determines how to represent and format common data types such as numeric values ​​and strings. Common type identifiers include:

  • s: string.
  • b: Binary integer format
  • d: decimal integer (integer)
  • o: Octal integer format
  • x: lowercase hexadecimal.
  • X: Hexadecimal capitalization.
  • c: Character format, convert integers into corresponding characters by unicode encoding
  • f: floating points (default floating points).
  • e: Scientific notation method represents floating points.
  • g: Scientific notation or floating point number (select the appropriate format according to accuracy).
  • %: Percent format, multiply the floating point by 100 and append the % symbol.

Value to decimal

>>> value = 0xff
>>> value
255
>>> print(f"{value:d}")
255

Priority conversion

&gt;&gt;&gt; a = 378297640000
&gt;&gt;&gt; 

#10 to 2&gt;&gt;&gt; print(f"{a:b}")
101100000010100010010111110010001000000

#10 to 8&gt;&gt;&gt; print(f"{a:d}")
378297640000

#10 to 16&gt;&gt;&gt; print(f"{a:x}")
58144be440

By default, no prefixes are added. You can add them using #

>>> a = 378297640000

>>> print(f"{a:#b}")
0b101100000010100010010111110010001000000

>>> print(f"{a:#d}")
378297640000

>>> print(f"{a:#x}")
0x58144be440

>>> print(f"{a:#X}")
0X58144BE440

Variable to floating point number

>>> value = 0xff

​​​​​​​>>> print(f"{value:f}")
255.000000
>>> 

Convert integers to unicode encoding corresponding characters

>>> a = 69
>>> print(f"{a:c}")
E
>>> a = 290
>>> print(f"{a:c}")
Ģ
>>> a = 2736
>>> print(f"{a:c}")
ર

Scientific Counting Method

>>> a = 378297640000
>>> 
>>> print(f"{a:e}")
3.782976e+11

>>> b = -0.132465
>>> 
>>> print(f"{b:e}")
-1.324650e-01

Percent sign

Multiply the floating point by 100 and append the % symbol

>>> a = 0.5473
>>> print(f"{a:%}")
54.730000%

2.6 Time format

fstring to implement formatting of time by combining the datetime module. More formats can be viewed by yourself.

>>> from datetime import datetime
>>> 
>>> now = ()
>>> 
>>> now
(2025, 5, 15, 17, 42, 6, 490934)
>>> formatted_time = f"{now:%Y-%m-%d %H:%M:%S}"
>>> print(formatted_time)
2025-05-15 17:42:06
>>> 

3. Comprehensive use

Floating point numbers are filled to 20 digits in the middle alignment to retain 2 decimal points

>>> a = 3.1415926

​​​​​​​>>> print(f"{a:-^20.2f}")
--------3.14--------

Integer padding to 30 bits right-aligned conversion to hexadecimal

>>> a = 378297640000

​​​​​​​>>> print(f"{a:+>30x}")
++++++++++++++++++++58144be440

The above is the detailed content of Python f-string to implement efficient string formatting. For more information about Python f-string string formatting, please pay attention to my other related articles!