Python formatting string f string Overview of Summary
- 2021-06-28 13:29:57
- OfStack
brief introduction
f-string, also known as the Format String Constant (formatted string literals), is a new string formatting method introduced by Python 3.6. This method originates from PEP 498 Literal String Interpolation and its main purpose is to make formatting strings easier.f-string is formally
f
or
F
Modifier-guided string (
f'xxx'
or
F'xxx'
), in braces
{}
Indicate the field being replaced;f-string is not essentially a string constant, but an expression that evaluates at run time:
While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
(Unlike other string constants with constant values, formatted strings are actually expressions that are evaluated by runtime operations.)
- Python Documentation
f-string is no less functional than the traditional%-formatting statement and
str.format()
Function, with better performance than 2 and simpler use, is recommended for Python 3.6 and later versions to use f-string for string formatting.
usage
This section mainly refers to the following materials:
Python Documentation Formatted String Literals
Python Documentation Format String Syntax
PEP 498 Literal String Interpolation
Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
Advanced usage of python3 f-string formatted strings
Python 3: An Intro to f-strings
Simple use
f-string in braces
{}
Represents the field being replaced, with the replacement directly filled in:
>>> 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'
Expression evaluation and function call
Braces for f-string
{}
You can fill in an expression or call a function, and Python will find the result and fill in the returned string:
>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'
>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'
>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'
>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'
Quotes, Braces and Backslashes
Quotations used within braces in f-string cannot conflict with quotation delimiters outside braces and can be switched flexibly as appropriate
'
and
"
:
>>> f'I am {"Eric"}'
'I am Eric'
>>> f'I am {'Eric'}'
File "<stdin>", line 1
f'I am {'Eric'}'
^
SyntaxError: invalid syntax
if
'
and
"
Not enough to meet the requirements, but can also be used
F
2
and
F
3
:
>>> f"He said {"I'm Eric"}"
File "<stdin>", line 1
f"He said {"I'm Eric"}"
^
SyntaxError: invalid syntax
>>> f'He said {"I'm Eric"}'
File "<stdin>", line 1
f'He said {"I'm Eric"}'
^
SyntaxError: invalid syntax
>>> f"""He said {"I'm Eric"}"""
"He said I'm Eric"
>>> f'''He said {"I'm Eric"}'''
"He said I'm Eric"
Quotes outside braces can also be used
F
4
Escape, but not in braces
F
4
Escape:
>>> f'''He\'ll say {"I'm Eric"}'''
"He'll say I'm Eric"
>>> f'''He'll say {"I\'m Eric"}'''
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
If braces need to be displayed outside the f-string braces, enter two consecutive braces
F
6
and
F
7
:
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'
As mentioned above, f-string braces cannot be used
F
4
Escape, in fact, is not allowed in f-string braces at all
F
4
.If really needed
F
4
Should first include
F
4
The content is represented by a variable, then the variable name is filled in the f-string braces:
>>> f"newline: {ord('\n')}"
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
>>> newline = ord('\n')
>>> f'newline: {newline}'
'newline: 10'
Multiline f-string
f-string can also be used for multiline strings:
>>> name = 'Eric'
>>> age = 27
>>> f"Hello!" \
... f"I'm {name}." \
... f"I'm {age}."
"Hello!I'm Eric.I'm 27."
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."
Custom format: Alignment, Width, Symbol, Zero, Precision, Binary, etc.
f-string Adopted
f'xxx'
2
Set the string format, where
f'xxx'
3
Is what replaces and fills in a string, which can be a variable, an expression, a function, etc.
f'xxx'
4
Is a format descriptor.You do not have to specify a default format
f'xxx'
5Write only as shown in the example above
f'xxx'
6
That's it.
Detailed syntax and meaning of format descriptors can be found in the official Python documentation. Here is a brief description of the meaning and function of commonly used format descriptors in the order in which they are used:
格式描述符 | 含义与作用 |
---|---|
< | 左对齐(字符串默认对齐方式) |
> | 右对齐(数值默认对齐方式) |
^ | 居中 |
Digital Symbol Related Format Descriptor
格式描述符 | 含义与作用 |
---|---|
+ | 负数前加负号(-),正数前加正号(+) |
- | 负数前加负号(-),正数前不加任何符号(默认) |
(空格) | 负数前加负号(-),正数前加1个空格 |
Note: Only applicable to numeric types.
Format descriptors related to how numbers are displayed
格式描述符 | 含义与作用 |
---|---|
# | 切换数字显示方式 |
Note 1: Applicable only to numeric types.
Note 2:
f'xxx'
7
The effects of different numerical types are different, as detailed in the following table:
数值类型 | 不加 CODE_TAG_REPLACE_MARK_27 (默认) | 加 CODE_TAG_REPLACE_MARK_27 | 区别 |
---|---|---|---|
2进制整数 | CODE_TAG_REPLACE_MARK_30 | CODE_TAG_REPLACE_MARK_31 | 开头是否显示 CODE_TAG_REPLACE_MARK_32 |
8进制整数 | CODE_TAG_REPLACE_MARK_33 | CODE_TAG_REPLACE_MARK_34 | 开头是否显示 CODE_TAG_REPLACE_MARK_35 |
10进制整数 | CODE_TAG_REPLACE_MARK_36 | CODE_TAG_REPLACE_MARK_36 | 无区别 |
106进制整数(小写字母) | CODE_TAG_REPLACE_MARK_38 | CODE_TAG_REPLACE_MARK_39 | 开头是否显示 CODE_TAG_REPLACE_MARK_40 |
106进制整数(大写字母) | CODE_TAG_REPLACE_MARK_41 | CODE_TAG_REPLACE_MARK_42 | 开头是否显示 CODE_TAG_REPLACE_MARK_43 |
Width and precision-related format descriptors
格式描述符 | 含义与作用 |
---|---|
CODE_TAG_REPLACE_MARK_44 | 整数 CODE_TAG_REPLACE_MARK_44 指定宽度 |
CODE_TAG_REPLACE_MARK_46 | 整数 CODE_TAG_REPLACE_MARK_44 指定宽度,开头的 CODE_TAG_REPLACE_MARK_48 指定高位用 CODE_TAG_REPLACE_MARK_48 补足宽度 |
CODE_TAG_REPLACE_MARK_50 | 整数 CODE_TAG_REPLACE_MARK_44 指定宽度,整数 CODE_TAG_REPLACE_MARK_52 指定显示精度 |
Note 1:
0width
It is not available for complex and non-numeric types.
str.format()
0
Not available for integer type.
Note 2:
str.format()
0
Floating and complex numbers for different format types have different meanings:
f
,
F
,
str.format()
8
,
str.format()
9
and
{}
0
time
str.format()
2
Specifies the number of digits after the decimal point, used for
{}
2
and
{}
3
time
str.format()
2
Specifies the number of valid digits (the first digit of a decimal point + the last digit of a decimal point).
Note 3:
str.format()
0
In addition to floating-point numbers, complex numbers can also be used in strings, where
str.format()
2
Meaning is to use only the first part of the string
str.format()
2
Bit character.
Example:
>>> a = 123.456
>>> f'a is {a:8.2f}'
'a is 123.46'
>>> f'a is {a:08.2f}'
'a is 00123.46'
>>> f'a is {a:8.2e}'
'a is 1.23e+02'
>>> f'a is {a:8.2%}'
'a is 12345.60%'
>>> f'a is {a:8.2g}'
'a is 1.2e+02'
>>> s = 'hello'
>>> f's is {s:8s}'
's is hello '
>>> f's is {s:8.3s}'
's is hel '
Thousands Separator Related Format Descriptor
格式描述符 | 含义与作用 |
---|---|
, | 使用,作为千位分隔符 |
_ | 使用_作为千位分隔符 |
Note 1: If not specified
{}
8
or
{}
9
, f-string does not use any thousands separator, which is the default.
Note 2:
{}
8
Applicable only to floating point, complex and 10-digit integers: for floating point and complex numbers,
{}
8
Separate only the digits before the decimal point.
Note 3:
{}
9
For floating point, complex and 2.8.10.106 binary integers: for floating point and complex numbers,
{}
9
Separate only the digits before the decimal point;For 2.8.106-bit integers, insert one at every 4-bit interval, fixed from low to high
{}
9
(10-digit integers are inserted 1 at every 3 digits
{}
9
).
Example:
>>> a = 1234567890.098765
>>> f'a is {a:f}'
'a is 1234567890.098765'
>>> f'a is {a:,f}'
'a is 1,234,567,890.098765'
>>> f'a is {a:_f}'
'a is 1_234_567_890.098765'
>>> b = 1234567890
>>> f'b is {b:_b}'
'b is 100_1001_1001_0110_0000_0010_1101_0010'
>>> f'b is {b:_o}'
'b is 111_4540_1322'
>>> f'b is {b:_d}'
'b is 1_234_567_890'
>>> f'b is {b:_x}'
'b is 4996_02d2'
Format Type Related Format Descriptors
Basic Format Type
格式描述符 | 含义与作用 | 适用变量类型 |
---|---|---|
CODE_TAG_REPLACE_MARK_76 | 普通字符串格式 | 字符串 |
CODE_TAG_REPLACE_MARK_77 | 2进制整数格式 | 整数 |
CODE_TAG_REPLACE_MARK_78 | 字符格式,按unicode编码将整数转换为对应字符 | 整数 |
CODE_TAG_REPLACE_MARK_79 | 10进制整数格式 | 整数 |
CODE_TAG_REPLACE_MARK_80 | 8进制整数格式 | 整数 |
CODE_TAG_REPLACE_MARK_81 | 106进制整数格式(小写字母) | 整数 |
CODE_TAG_REPLACE_MARK_82 | 106进制整数格式(大写字母) | 整数 |
CODE_TAG_REPLACE_MARK_58 | 科学计数格式,以 CODE_TAG_REPLACE_MARK_58 表示 CODE_TAG_REPLACE_MARK_85 | 浮点数、复数、整数(自动转换为浮点数) |
CODE_TAG_REPLACE_MARK_59 | 与 CODE_TAG_REPLACE_MARK_58 等价,但以 CODE_TAG_REPLACE_MARK_59 表示 CODE_TAG_REPLACE_MARK_85 | 浮点数、复数、整数(自动转换为浮点数) |
CODE_TAG_REPLACE_MARK_0 | 定点数格式,默认精度( CODE_TAG_REPLACE_MARK_52 )是6 | 浮点数、复数、整数(自动转换为浮点数) |
CODE_TAG_REPLACE_MARK_1 | 与 CODE_TAG_REPLACE_MARK_0 等价,但将 CODE_TAG_REPLACE_MARK_94 和 CODE_TAG_REPLACE_MARK_95 换成 CODE_TAG_REPLACE_MARK_96 和 CODE_TAG_REPLACE_MARK_97 | 浮点数、复数、整数(自动转换为浮点数) |
CODE_TAG_REPLACE_MARK_62 | 通用格式,小数用 CODE_TAG_REPLACE_MARK_0 ,大数用 CODE_TAG_REPLACE_MARK_58 | 浮点数、复数、整数(自动转换为浮点数) |
CODE_TAG_REPLACE_MARK_63 | 与 CODE_TAG_REPLACE_MARK_63 等价,但小数用 CODE_TAG_REPLACE_MARK_1 ,大数用 CODE_TAG_REPLACE_MARK_59 | 浮点数、复数、整数(自动转换为浮点数) |
CODE_TAG_REPLACE_MARK_60 | 百分比格式,数字自动乘上100后按 CODE_TAG_REPLACE_MARK_0 格式排版,并加 CODE_TAG_REPLACE_MARK_60 后缀 | 浮点数、整数(自动转换为浮点数) |
Common special format types: Standard Library
datetime
The type of format given for typesetting time information, applicable to
date
,
datetime
and
F
11
object
格式描述符 | 含义 | 显示样例 |
---|---|---|
CODE_TAG_REPLACE_MARK_112 | 星期几(缩写) | CODE_TAG_REPLACE_MARK_113 |
CODE_TAG_REPLACE_MARK_114 | 星期几(全名) | CODE_TAG_REPLACE_MARK_115 |
CODE_TAG_REPLACE_MARK_116 | 星期几(数字, CODE_TAG_REPLACE_MARK_48 是周日, CODE_TAG_REPLACE_MARK_118 是周6) | CODE_TAG_REPLACE_MARK_119 |
CODE_TAG_REPLACE_MARK_120 | 星期几(数字, CODE_TAG_REPLACE_MARK_121 是周1, CODE_TAG_REPLACE_MARK_122 是周日) | CODE_TAG_REPLACE_MARK_123 |
CODE_TAG_REPLACE_MARK_124 | 日(数字,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_126 |
CODE_TAG_REPLACE_MARK_127 | 月(缩写) | CODE_TAG_REPLACE_MARK_128 |
CODE_TAG_REPLACE_MARK_129 | 月(全名) | CODE_TAG_REPLACE_MARK_130 |
CODE_TAG_REPLACE_MARK_131 | 月(数字,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_133 |
CODE_TAG_REPLACE_MARK_134 | 年(后两位数字,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_136 |
CODE_TAG_REPLACE_MARK_137 | 年(完整数字,不补零) | CODE_TAG_REPLACE_MARK_138 |
CODE_TAG_REPLACE_MARK_139 | 小时(24小时制,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_141 |
CODE_TAG_REPLACE_MARK_142 | 小时(12小时制,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_144 |
CODE_TAG_REPLACE_MARK_145 | 上午/下午 | CODE_TAG_REPLACE_MARK_146 |
CODE_TAG_REPLACE_MARK_147 | 分钟(以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_141 |
CODE_TAG_REPLACE_MARK_150 | 秒钟(以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_152 |
CODE_TAG_REPLACE_MARK_153 | 微秒(以 CODE_TAG_REPLACE_MARK_48 补足6位) | CODE_TAG_REPLACE_MARK_155 |
CODE_TAG_REPLACE_MARK_156 | UTC偏移量(格式是 CODE_TAG_REPLACE_MARK_157 ,未指定时区则返回空字符串) | CODE_TAG_REPLACE_MARK_158 |
CODE_TAG_REPLACE_MARK_159 | 时区名(未指定时区则返回空字符串) | CODE_TAG_REPLACE_MARK_160 |
CODE_TAG_REPLACE_MARK_161 | 1年中的第几天(以 CODE_TAG_REPLACE_MARK_48 补足3位) | CODE_TAG_REPLACE_MARK_163 |
CODE_TAG_REPLACE_MARK_164 | 1年中的第几周(以全年首个周日后的星期为第0周,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_166 |
CODE_TAG_REPLACE_MARK_116 | 1年中的第几周(以全年首个周1后的星期为第0周,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_169 |
CODE_TAG_REPLACE_MARK_170 | 1年中的第几周(以全年首个包含1月4日的星期为第1周,以 CODE_TAG_REPLACE_MARK_48 补足两位) | CODE_TAG_REPLACE_MARK_169 |
Comprehensive example
>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'
>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'
>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'
>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'
0
lambda expression
f-string braces can also be filled with an lambda expression, but the lambda expression's
F
73
The f-string is mistaken for the separator between the expression and the format descriptor. To avoid ambiguity, the lambda expression needs to be placed in parentheses
F
74
Internal:
>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'
>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'
>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'
>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'
1