当前位置:网站首页>史上最易懂的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 中最常用的一些操作,如需了解更多,可前往官方文档进一步学习。
边栏推荐
- excel表格中选中单元格出现十字带阴影的选中效果
- R HISTOGRAM EXAMPLE QUICK REFERENCE
- Attribute acquisition method and operation notes of C # multidimensional array
- How to Easily Create Barplots with Error Bars in R
- GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
- HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
- b格高且好看的代码片段分享图片生成
- bedtools使用教程
- A white hole formed by antineutrons produced by particle accelerators
- GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
猜你喜欢
Never forget, there will be echoes | hanging mirror sincerely invites you to participate in the opensca user award research
YYGH-BUG-05
R HISTOGRAM EXAMPLE QUICK REFERENCE
How to Add P-Values onto Horizontal GGPLOTS
【2022 ACTF-wp】
Seriation in R: How to Optimally Order Objects in a Data Matrice
Seriation in R: How to Optimally Order Objects in a Data Matrice
动态内存(进阶四)
How to Create a Beautiful Plots in R with Summary Statistics Labels
File operation (detailed!)
随机推荐
Mish-撼动深度学习ReLU激活函数的新继任者
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
基于 Openzeppelin 的可升级合约解决方案的注意事项
GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT
揭露数据不一致的利器 —— 实时核对系统
文件操作(详解!)
【2022 ACTF-wp】
BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
Tiktok overseas tiktok: finalizing the final data security agreement with Biden government
php 根据经纬度查询距离
The selected cells in Excel form have the selection effect of cross shading
A white hole formed by antineutrons produced by particle accelerators
Mmrotate rotation target detection framework usage record
Log4j2
数据分析 - matplotlib示例代码
GGPlot Examples Best Reference
Tdsql | difficult employment? Tencent cloud database micro authentication to help you
Flesh-dect (media 2021) -- a viewpoint of material decomposition
Industry analysis
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement