当前位置:网站首页>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 .
边栏推荐
猜你喜欢

基于Hardhat和Openzeppelin开发可升级合约(一)

Flesh-dect (media 2021) -- a viewpoint of material decomposition

Develop scalable contracts based on hardhat and openzeppelin (II)

Dynamic debugging of multi file program x32dbg

自然语言处理系列(一)——RNN基础

还不会安装WSL 2?看这一篇文章就够了

HOW TO ADD P-VALUES TO GGPLOT FACETS

预言机链上链下调研

PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)

How to Easily Create Barplots with Error Bars in R
随机推荐
MySql存储过程游标遍历结果集
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
to_bytes与from_bytes简单示例
PyTorch搭建LSTM实现服装分类(FashionMNIST)
excel表格中选中单元格出现十字带阴影的选中效果
XSS labs master shooting range environment construction and 1-6 problem solving ideas
How to Add P-Values onto Horizontal GGPLOTS
行業的分析
多文件程序X32dbg动态调试
Precautions for scalable contract solution based on openzeppelin
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
浅谈sklearn中的数据预处理
Fabric.js 3个api设置画布宽高
Log4j2
【2022 ACTF-wp】
BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
进入前六!博云在中国云管理软件市场销量排行持续上升
Writing contract test cases based on hardhat
HOW TO CREATE A BEAUTIFUL INTERACTIVE HEATMAP IN R
Tiktok overseas tiktok: finalizing the final data security agreement with Biden government