当前位置:网站首页>史上最易懂的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 中最常用的一些操作,如需了解更多,可前往官方文檔進一步學習。
边栏推荐
- Cmake cross compilation
- flutter 问题总结
- [visual studio 2019] create MFC desktop program (install MFC development components | create MFC application | edit MFC application window | add click event for button | Modify button text | open appl
- HOW TO ADD P-VALUES TO GGPLOT FACETS
- conda常用命令汇总
- 【2022 ACTF-wp】
- [visual studio 2019] create and import cmake project
- 进入前六!博云在中国云管理软件市场销量排行持续上升
- to_bytes与from_bytes简单示例
- How to Create a Beautiful Plots in R with Summary Statistics Labels
猜你喜欢

H5, add a mask layer to the page, which is similar to clicking the upper right corner to open it in the browser

Power Spectral Density Estimates Using FFT---MATLAB

SVO2系列之深度滤波DepthFilter

How to Create a Beautiful Plots in R with Summary Statistics Labels

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

Research on and off the Oracle chain

How to Visualize Missing Data in R using a Heatmap

From scratch, develop a web office suite (3): mouse events

预言机链上链下调研

YYGH-BUG-05
随机推荐
XSS labs master shooting range environment construction and 1-6 problem solving ideas
The position of the first underline selected by the vant tabs component is abnormal
YYGH-10-微信支付
What week is a date obtained by QT
PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)
B high and beautiful code snippet sharing image generation
MySQL comparison operator in problem solving
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
通讯录的实现(文件版本)
Dynamic debugging of multi file program x32dbg
Seriation in R: How to Optimally Order Objects in a Data Matrice
PHP query distance according to longitude and latitude
deepTools对ChIP-seq数据可视化
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
PgSQL string is converted to array and associated with other tables, which are displayed in the original order after matching and splicing
HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
基于 Openzeppelin 的可升级合约解决方案的注意事项
小程序链接生成
揭露数据不一致的利器 —— 实时核对系统
Mish-撼动深度学习ReLU激活函数的新继任者