当前位置:网站首页>The most understandable f-string tutorial in history, collecting this one is enough
The most understandable f-string tutorial in history, collecting this one is enough
2022-07-02 12:00:00 【raelum】
Catalog
One 、 Preface
Following %
、format
After the formatting ,Python 3.6 Began to introduce a more efficient string formatting :f-string.
f-string In form f
Modifier LED string (f''
), In the string {}
Indicates the field to be replaced .f-string In essence, it is not a string constant , It's an expression that evaluates at run time .
Two 、 Basic operation
f-string Medium {}
Represents the field to be replaced , Here's an example
""" Comparison of three ways of formatting strings """
name = 'raelum'
print('%s' % name)
# raelum
print('{}'.format(name))
# raelum
print(f'{
name}')
# raelum
As I said before ,{}
in What is actually stored is the value of the expression , This means that we can be in {}
Carry out operations :
name = 'raelum'
print(f'{
name.upper()}')
# RAELUM
print(f'{
name + name.capitalize()}')
# raelumRaelum
print(f'{
name[:-1]}')
# raelu
""" More examples One """
print(f'{
2 * 3 + 5}')
# 11
print(f'{
sum([i for i in range(10)])}')
# 45
print(f'{
[i ** 2 for i in range(3)]}')
# [0, 1, 4]
""" More examples Two """
name = 'Li Hua'
num = 13
print(f'My name is {
name}.')
# My name is Li Hua.
print(f'I have {
num} apples.')
# I have 13 apples.
3、 ... and 、 Quotation mark specification
f-string in {}
Quotation marks used inside cannot be compared with {}
The quotation mark delimiter outside conflicts , That is, the following operations are not allowed :
print(f'My name is {'Li Hua'}')
# SyntaxError: f-string: expecting '}'
It can be output normally in any of the following forms ( All the possible situations are listed below ):
""" The outer delimiter is a single quotation mark """
print(f'My name is {
"Li Hua"}')
print(f'My name is {
"""Li Hua"""}')
""" The outer delimiter is a double quotation mark """
print(f"My name is {
'Li Hua'}")
print(f"My name is {
'''Li Hua'''}")
""" The outer delimiter is double three quotation marks """
print(f"""My name is {
'Li Hua'}""")
print(f"""My name is {
"Li Hua"}""")
print(f"""My name is {
'''Li Hua'''}""")
""" The outer delimiter is a single three quotation mark """
print(f'''My name is {
'Li Hua'}''')
print(f'''My name is {
"Li Hua"}''')
print(f'''My name is {
"""Li Hua"""}''')
summary : If there are many kinds of quotation marks inside the string, but you don't want to worry about quotation marks , External delimiters are used directly """
That's it .
Four 、 The problem of escape
f-string Can't be in {}
Internal use escape , But in {}
Escape outside , as follows :
print(f"{
'\''}")
# SyntaxError: f-string expression part cannot include a backslash
print(f"\'")
# '
If it really needs to be in {}
Use the escape , Should contain \
The content of is declared as a variable separately
s = '\''
print(f"{
s}")
# '
5、 ... and 、 alignment
f-string Of {}
Used in content:format
To set the string format , To use the default format , You don't have to specify :format
.
5.1 By default, spaces are used to fill
name = 'raelum'
print(f'{
name:>20}') # Right alignment , Fill string length to 20
# raelum
print(f'{
name:<20}') # Align left , Fill string length to 20
# raelum
print(f'{
name:^20}') # Align center , Fill string length to 20
# raelum
5.2 Fill with other characters
name = 'raelum'
print(f'{
name:a>20}')
# aaaaaaaaaaaaaaraelum
print(f'{
name:1<20}')
# raelum11111111111111
print(f'{
name:-^20}')
# -------raelum-------
6、 ... and 、 Width and precision
Format descriptor | effect |
---|---|
width | Integers width Specify the width |
0width | Integers width Specify the width ,0 For high order, use 0 Make up width |
width.precision | Integers width Specify the width ,precision Specify the precision |
When given precision
when ,width
Omission .
import numpy as np
""" Example 1 """
a = 123456
print(f'{
a:4}')
# 123456
print(f'{
a:8}')
# 123456
print(f'{
a:08}')
# 00123456
""" Example 2 """
b = np.pi
print(f'{
b:.3f}')
# 3.142
print(f'{
b:8.3f}')
# 3.142
print(f'{
b:08.3f}')
# 0003.142
Last
This article only introduces f-string Some of the most commonly used operations in , To learn more , You can go to Official documents Further study .
边栏推荐
- Pyqt5+opencv project practice: microcirculator pictures, video recording and manual comparison software (with source code)
- Develop scalable contracts based on hardhat and openzeppelin (II)
- 史上最易懂的f-string教程,收藏這一篇就够了
- R HISTOGRAM EXAMPLE QUICK REFERENCE
- HOW TO ADD P-VALUES TO GGPLOT FACETS
- BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
- QT meter custom control
- PyTorch中repeat、tile与repeat_interleave的区别
- Analyse de l'industrie
- PX4 Position_Control RC_Remoter引入
猜你喜欢
YYGH-BUG-05
Esp32 stores the distribution network information +led displays the distribution network status + press the key to clear the distribution network information (source code attached)
How to Add P-Values onto Horizontal GGPLOTS
Applet link generation
机械臂速成小指南(七):机械臂位姿的描述方法
Research on and off the Oracle chain
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
Mish-撼动深度学习ReLU激活函数的新继任者
Tiktok overseas tiktok: finalizing the final data security agreement with Biden government
PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)
随机推荐
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
C # method of obtaining a unique identification number (ID) based on the current time
Le tutoriel F - String le plus facile à comprendre de l'histoire.
Mish shake the new successor of the deep learning relu activation function
FLESH-DECT(MedIA 2021)——一个material decomposition的观点
[QT] Qt development environment installation (QT version 5.14.2 | QT download | QT installation)
QT meter custom control
How to Create a Nice Box and Whisker Plot in R
How to Visualize Missing Data in R using a Heatmap
时间格式化显示
Three transparent LED displays that were "crowded" in 2022
Pytorch builds LSTM to realize clothing classification (fashionmnist)
Dynamic memory (advanced 4)
php 根据经纬度查询距离
Tiktok overseas tiktok: finalizing the final data security agreement with Biden government
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
Repeat, tile and repeat in pytorch_ The difference between interleave
Larvel modify table fields
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
Mish-撼动深度学习ReLU激活函数的新继任者