当前位置:网站首页>史上最易懂的f-string教程,收藏這一篇就够了
史上最易懂的f-string教程,收藏這一篇就够了
2022-07-02 12:00: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 中最常用的一些操作,如需了解更多,可前往官方文檔進一步學習。
边栏推荐
- Larvel modify table fields
- conda常用命令汇总
- 电脑无缘无故黑屏,无法调节亮度。
- [untitled] how to mount a hard disk in armbian
- PgSQL string is converted to array and associated with other tables, which are displayed in the original order after matching and splicing
- Filtre de profondeur de la série svo2
- GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
- Mmrotate rotation target detection framework usage record
- BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
- HOW TO ADD P-VALUES ONTO A GROUPED GGPLOT USING THE GGPUBR R PACKAGE
猜你喜欢
ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)
2022年遭“挤爆”的三款透明LED显示屏
ESP32 Arduino 引入LVGL 碰到的一些问题
XSS labs master shooting range environment construction and 1-6 problem solving ideas
PyTorch nn.RNN 参数全解析
6方面带你认识LED软膜屏 LED软膜屏尺寸|价格|安装|应用
Some problems encountered in introducing lvgl into esp32 Arduino
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
GGPlot Examples Best Reference
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
随机推荐
How to Create a Nice Box and Whisker Plot in R
【2022 ACTF-wp】
Cmake cross compilation
Read the Flink source code and join Alibaba cloud Flink group..
HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
How to Create a Beautiful Plots in R with Summary Statistics Labels
ORB-SLAM2不同线程间的数据共享与传递
PHP query distance according to longitude and latitude
YYGH-BUG-04
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
Easyexcel and Lombok annotations and commonly used swagger annotations
Take you ten days to easily finish the finale of go micro services (distributed transactions)
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
to_bytes与from_bytes简单示例
Dynamic memory (advanced 4)
【2022 ACTF-wp】
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
ESP32音频框架 ESP-ADF 添加按键外设流程代码跟踪
Data analysis - Matplotlib sample code
xss-labs-master靶场环境搭建与1-6关解题思路