当前位置:网站首页>史上最易懂的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 中最常用的一些操作,如需了解更多,可前往官方文檔進一步學習。
边栏推荐
- H5, add a mask layer to the page, which is similar to clicking the upper right corner to open it in the browser
- K-Means Clustering Visualization in R: Step By Step Guide
- HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
- Mish shake the new successor of the deep learning relu activation function
- Some problems encountered in introducing lvgl into esp32 Arduino
- GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT
- YYGH-BUG-05
- File operation (detailed!)
- Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
- vant tabs组件选中第一个下划线位置异常
猜你喜欢

GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R

6方面带你认识LED软膜屏 LED软膜屏尺寸|价格|安装|应用

ESP32音频框架 ESP-ADF 添加按键外设流程代码跟踪

小程序链接生成

GGPUBR: HOW TO ADD ADJUSTED P-VALUES TO A MULTI-PANEL GGPLOT

文件操作(详解!)

K-Means Clustering Visualization in R: Step By Step Guide

预言机链上链下调研

SVO2系列之深度濾波DepthFilter

Read the Flink source code and join Alibaba cloud Flink group..
随机推荐
Analyse de l'industrie
Develop scalable contracts based on hardhat and openzeppelin (II)
ESP32 Arduino 引入LVGL 碰到的一些问题
How to Create a Nice Box and Whisker Plot in R
自然语言处理系列(一)——RNN基础
CMake交叉编译
2022年遭“挤爆”的三款透明LED显示屏
How to Add P-Values onto Horizontal GGPLOTS
excel表格中选中单元格出现十字带阴影的选中效果
小程序链接生成
What is the relationship between digital transformation of manufacturing industry and lean production
Mmrotate rotation target detection framework usage record
ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)
HOW TO ADD P-VALUES TO GGPLOT FACETS
Pytorch builds LSTM to realize clothing classification (fashionmnist)
The computer screen is black for no reason, and the brightness cannot be adjusted.
BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
时间格式化显示
【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
史上最易懂的f-string教程,收藏这一篇就够了