当前位置:网站首页>史上最易懂的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 中最常用的一些操作,如需了解更多,可前往官方文档进一步学习。
边栏推荐
- MySQL comparison operator in problem solving
- 【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
- A sharp tool for exposing data inconsistencies -- a real-time verification system
- Dynamic debugging of multi file program x32dbg
- FLESH-DECT(MedIA 2021)——一个material decomposition的观点
- Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
- 可升级合约的原理-DelegateCall
- 2022年遭“挤爆”的三款透明LED显示屏
- YYGH-BUG-05
- Flesh-dect (media 2021) -- a viewpoint of material decomposition
猜你喜欢

YYGH-BUG-04

Read the Flink source code and join Alibaba cloud Flink group..

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

The position of the first underline selected by the vant tabs component is abnormal

How to Easily Create Barplots with Error Bars in R

揭露数据不一致的利器 —— 实时核对系统

Some problems encountered in introducing lvgl into esp32 Arduino

A sharp tool for exposing data inconsistencies -- a real-time verification system

PgSQL string is converted to array and associated with other tables, which are displayed in the original order after matching and splicing

Mish shake the new successor of the deep learning relu activation function
随机推荐
Visualization of chip SEQ data by deeptools
进入前六!博云在中国云管理软件市场销量排行持续上升
Power Spectral Density Estimates Using FFT---MATLAB
HOW TO CREATE A BEAUTIFUL INTERACTIVE HEATMAP IN R
php 根据经纬度查询距离
Fabric. JS 3 APIs to set canvas width and height
YYGH-BUG-04
excel表格中选中单元格出现十字带阴影的选中效果
Principe du contrat évolutif - delegatecall
Log4j2
What is the relationship between digital transformation of manufacturing industry and lean production
Bedtools tutorial
deepTools对ChIP-seq数据可视化
flutter 问题总结
预言机链上链下调研
K-Means Clustering Visualization in R: Step By Step Guide
小程序链接生成
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
Three transparent LED displays that were "crowded" in 2022
XSS labs master shooting range environment construction and 1-6 problem solving ideas