当前位置:网站首页>史上最易懂的f-string教程,收藏这一篇就够了
史上最易懂的f-string教程,收藏这一篇就够了
2022-07-02 09:42:00 【raelum】
一、前言
继 %
、format
格式化后,Python 3.6 开始引入了一种效率更高的字符串格式化方式:f-string。
f-string 在形式上是以 f
修饰符引领的字符串(f''
),字符串中的 {}
表明将要被替换的字段。f-string 在本质上并不是字符串常量,而是一个在运行时运算求值的表达式。
二、基本操作
f-string 中的 {}
表示将要被替换的字段,如下例
""" 三种格式化字符串方式的比较 """
name = 'raelum'
print('%s' % name)
# raelum
print('{}'.format(name))
# raelum
print(f'{
name}')
# raelum
前面说过,{}
中实际上存放的是表达式的值,这意味着我们可以在 {}
进行运算:
name = 'raelum'
print(f'{
name.upper()}')
# RAELUM
print(f'{
name + name.capitalize()}')
# raelumRaelum
print(f'{
name[:-1]}')
# raelu
""" 更多的例子 一"""
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]
""" 更多的例子 二"""
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.
三、引号规范
f-string 中 {}
内使用的引号不能与 {}
外的引号定界符冲突,即如下这样的操作是不可以的:
print(f'My name is {'Li Hua'}')
# SyntaxError: f-string: expecting '}'
改为以下任何一种形式都能够正常输出(以下列举了所有可能的情况):
""" 外部定界符是单引号 """
print(f'My name is {
"Li Hua"}')
print(f'My name is {
"""Li Hua"""}')
""" 外部定界符是双引号 """
print(f"My name is {
'Li Hua'}")
print(f"My name is {
'''Li Hua'''}")
""" 外部定界符是双三引号 """
print(f"""My name is {
'Li Hua'}""")
print(f"""My name is {
"Li Hua"}""")
print(f"""My name is {
'''Li Hua'''}""")
""" 外部定界符是单三引号 """
print(f'''My name is {
'Li Hua'}''')
print(f'''My name is {
"Li Hua"}''')
print(f'''My name is {
"""Li Hua"""}''')
总结:如果字符串内部可能会出现多种引号但又不想操心引号问题,外部定界符直接使用 """
就行了。
四、转义问题
f-string 不能在 {}
内使用转义,但可在 {}
外进行转义,如下:
print(f"{
'\''}")
# SyntaxError: f-string expression part cannot include a backslash
print(f"\'")
# '
如果确实需要在 {}
使用转义,则应当将包含 \
的内容单独声明为一个变量
s = '\''
print(f"{
s}")
# '
五、对齐
f-string 的 {}
中采用 content:format
的方式来设置字符串格式,如要使用默认格式,则可不必指定 :format
。
5.1 默认使用空格填充
name = 'raelum'
print(f'{
name:>20}') # 右对齐,填充字符串长度至20
# raelum
print(f'{
name:<20}') # 左对齐,填充字符串长度至20
# raelum
print(f'{
name:^20}') # 居中对齐,填充字符串长度至20
# raelum
5.2 使用其他字符填充
name = 'raelum'
print(f'{
name:a>20}')
# aaaaaaaaaaaaaaraelum
print(f'{
name:1<20}')
# raelum11111111111111
print(f'{
name:-^20}')
# -------raelum-------
六、宽度与精度
格式描述符 | 作用 |
---|---|
width | 整数 width 指定宽度 |
0width | 整数 width 指定宽度,0 表示高位用 0 补足宽度 |
width.precision | 整数 width 指定宽度,precision 指定精度 |
当给定 precision
时,width
可省略。
import numpy as np
""" 示例一 """
a = 123456
print(f'{
a:4}')
# 123456
print(f'{
a:8}')
# 123456
print(f'{
a:08}')
# 00123456
""" 示例二 """
b = np.pi
print(f'{
b:.3f}')
# 3.142
print(f'{
b:8.3f}')
# 3.142
print(f'{
b:08.3f}')
# 0003.142
最后
本文仅介绍了 f-string 中最常用的一些操作,如需了解更多,可前往官方文档进一步学习。
边栏推荐
- From scratch, develop a web office suite (3): mouse events
- Flesh-dect (media 2021) -- a viewpoint of material decomposition
- How to Add P-Values onto Horizontal GGPLOTS
- Seriation in R: How to Optimally Order Objects in a Data Matrice
- Log4j2
- Amazon cloud technology community builder application window opens
- 电脑无缘无故黑屏,无法调节亮度。
- The selected cells in Excel form have the selection effect of cross shading
- 通讯录的实现(文件版本)
- What week is a date obtained by QT
猜你喜欢
基于Hardhat和Openzeppelin开发可升级合约(二)
PyTorch搭建LSTM实现服装分类(FashionMNIST)
深入理解PyTorch中的nn.Embedding
自然语言处理系列(三)——LSTM
6方面带你认识LED软膜屏 LED软膜屏尺寸|价格|安装|应用
Mish shake the new successor of the deep learning relu activation function
Seriation in R: How to Optimally Order Objects in a Data Matrice
YYGH-BUG-05
数据分析 - matplotlib示例代码
自然语言处理系列(二)——使用RNN搭建字符级语言模型
随机推荐
小程序链接生成
Power Spectral Density Estimates Using FFT---MATLAB
Log4j2
A white hole formed by antineutrons produced by particle accelerators
2022年遭“挤爆”的三款透明LED显示屏
Data analysis - Matplotlib sample code
HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
【2022 ACTF-wp】
YYGH-BUG-04
Larvel modify table fields
Summary of flutter problems
Research on and off the Oracle chain
多文件程序X32dbg动态调试
Is it safe to open a stock account through the QR code of the securities manager? Or is it safe to open an account in a securities company?
C # method of obtaining a unique identification number (ID) based on the current time
PyTorch中repeat、tile与repeat_interleave的区别
基于Hardhat编写合约测试用例
K-Means Clustering Visualization in R: Step By Step Guide
揭露数据不一致的利器 —— 实时核对系统
Principle of scalable contract delegatecall