当前位置:网站首页>史上最易懂的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 中最常用的一些操作,如需了解更多,可前往官方文档进一步学习。
边栏推荐
- [visual studio 2019] create and import cmake project
- Dynamic debugging of multi file program x32dbg
- PHP query distance according to longitude and latitude
- Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
- Map set assignment to database
- HOW TO ADD P-VALUES TO GGPLOT FACETS
- ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)
- How to Visualize Missing Data in R using a Heatmap
- Larvel modify table fields
- A white hole formed by antineutrons produced by particle accelerators
猜你喜欢
![[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](/img/6a/111da81436659c7502648907ec1367.jpg)
[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

GGPlot Examples Best Reference

YYGH-BUG-05

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

Esp32 audio frame esp-adf add key peripheral process code tracking

GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL

小程序链接生成

YYGH-9-预约下单

File operation (detailed!)

自然语言处理系列(二)——使用RNN搭建字符级语言模型
随机推荐
Bedtools tutorial
YYGH-9-预约下单
CMake交叉编译
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
Log4j2
SVO2系列之深度滤波DepthFilter
Data analysis - Matplotlib sample code
bedtools使用教程
Never forget, there will be echoes | hanging mirror sincerely invites you to participate in the opensca user award research
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
Homer forecast motif
Cluster Analysis in R Simplified and Enhanced
Pyqt5+opencv project practice: microcirculator pictures, video recording and manual comparison software (with source code)
Yygh-10-wechat payment
6. Introduce you to LED soft film screen. LED soft film screen size | price | installation | application
YYGH-BUG-04
时间格式化显示
预言机链上链下调研
XSS labs master shooting range environment construction and 1-6 problem solving ideas