当前位置:网站首页>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 .
边栏推荐
- Dynamic debugging of multi file program x32dbg
- How to Create a Nice Box and Whisker Plot in R
- 行業的分析
- Implementation of address book (file version)
- to_bytes与from_bytes简单示例
- 浅谈sklearn中的数据预处理
- YYGH-BUG-04
- 史上最易懂的f-string教程,收藏這一篇就够了
- How to Add P-Values onto Horizontal GGPLOTS
- [untitled] how to mount a hard disk in armbian
猜你喜欢
HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
Small guide for rapid formation of manipulator (VII): description method of position and posture of manipulator
Dynamic memory (advanced 4)
[visual studio 2019] create MFC desktop program (install MFC development components | create MFC application | edit MFC application window | add click event for button | Modify button text | open appl
Natural language processing series (II) -- building character level language model using RNN
ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)
PgSQL string is converted to array and associated with other tables, which are displayed in the original order after matching and splicing
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
How to Create a Nice Box and Whisker Plot in R
The position of the first underline selected by the vant tabs component is abnormal
随机推荐
How to Visualize Missing Data in R using a Heatmap
GGPlot Examples Best Reference
YYGH-BUG-05
自然语言处理系列(二)——使用RNN搭建字符级语言模型
机械臂速成小指南(七):机械臂位姿的描述方法
Some problems encountered in introducing lvgl into esp32 Arduino
Larvel modify table fields
How to Easily Create Barplots with Error Bars in R
H5, add a mask layer to the page, which is similar to clicking the upper right corner to open it in the browser
史上最易懂的f-string教程,收藏這一篇就够了
MSI announced that its motherboard products will cancel all paper accessories
Repeat, tile and repeat in pytorch_ The difference between interleave
Seriation in R: How to Optimally Order Objects in a Data Matrice
Log4j2
qt 仪表自定义控件
数据分析 - matplotlib示例代码
The selected cells in Excel form have the selection effect of cross shading
to_bytes与from_bytes简单示例
Depth filter of SvO2 series
史上最易懂的f-string教程,收藏这一篇就够了