当前位置:网站首页>史上最易懂的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 中最常用的一些操作,如需了解更多,可前往官方文檔進一步學習。
边栏推荐
- Principe du contrat évolutif - delegatecall
- MySql存储过程游标遍历结果集
- [untitled] how to mount a hard disk in armbian
- The computer screen is black for no reason, and the brightness cannot be adjusted.
- HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
- HOW TO ADD P-VALUES ONTO A GROUPED GGPLOT USING THE GGPUBR R PACKAGE
- Dynamic memory (advanced 4)
- PgSQL string is converted to array and associated with other tables, which are displayed in the original order after matching and splicing
- 【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
- Esp32 audio frame esp-adf add key peripheral process code tracking
猜你喜欢
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)
XSS labs master shooting range environment construction and 1-6 problem solving ideas
Cluster Analysis in R Simplified and Enhanced
Data analysis - Matplotlib sample code
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
Principe du contrat évolutif - delegatecall
Pytorch builds LSTM to realize clothing classification (fashionmnist)
Develop scalable contracts based on hardhat and openzeppelin (I)
随机推荐
自然语言处理系列(一)——RNN基础
MySql存储过程游标遍历结果集
Implementation of address book (file version)
基于 Openzeppelin 的可升级合约解决方案的注意事项
How to Create a Nice Box and Whisker Plot in R
通讯录的实现(文件版本)
ESP32音频框架 ESP-ADF 添加按键外设流程代码跟踪
GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT
XSS labs master shooting range environment construction and 1-6 problem solving ideas
YYGH-BUG-05
Deep understanding of NN in pytorch Embedding
【2022 ACTF-wp】
[visual studio 2019] create and import cmake project
基于Hardhat编写合约测试用例
Principe du contrat évolutif - delegatecall
Pytorch builds LSTM to realize clothing classification (fashionmnist)
C # method of obtaining a unique identification number (ID) based on the current time
Three transparent LED displays that were "crowded" in 2022
How to Visualize Missing Data in R using a Heatmap
基于Hardhat和Openzeppelin开发可升级合约(一)