深入解析Python中的传统格式化字符串与f-string新特性

1.传统格式字符串

深入解析Python中的传统格式化字符串与f-string新特性

传统的格式化字符串是指%d、%f等占位符的使用,类似于Java或C语言中注释输出函数的作用。

name = 'tom'
age = 20
weight = 74.78
# 在字符串内使用占位符%d %s %f等指定格式, 在字符串后面使用%向格式化字符串传递参数
s = 'hello %s, your age is %d, and your weight is %f kg' %(name, age, weight)
print(s)

最常用的占位符包括

您还可以在 % 和以下字母之间插入辅助指令以进一步格式化字符串。

其中比较常用的是

2.f-string格式字符串

f-string,格式化字符串文字,是Python 3.6中新引入的字符串格式化方法。其目的是让格式化字符串的操作变得更加简单。形式上,f-string是以f或F修饰符(f'xxx'或F'xxx')开头的字符串,大括号{}表示被替换的字段; f-string 本质上不是字符串。一个常量,但是一个在运行时计算的表达式

f-string的功能并不逊于传统的%-formatting语句和str.format()函数,而且性能比两者都要好,而且使用起来更加简洁明了。因此,推荐使用Python 3.6及以上版本。 f-string 执行字符串格式化。

与传统的格式化字符串方法一样,您可以指定替换内容的宽度(字符数)。如果宽度不足,则默认填充空格。

下面的例子中,用< > ^这三个字符来表示宽度不足时的对齐方式,分别表示左对齐、右对齐和居中对齐。

In [2]: name = 'tom'
In [3]: age = 20
In [4]: pi = 3.14159
In [5]: f'hello{name}'
Out[5]: 'hellotom'
In [6]: f'hello{name:5}'
Out[6]: 'hellotom  '
In [7]: f'hello{name:>5}'
Out[7]: 'hello  tom'
In [8]: f'hello{name:<5}'
Out[8]: 'hellotom  '
In [9]: f'hello{name:^5}'
Out[9]: 'hello tom '

对于数字类型,可以指定宽度不足时在对齐字符之前填充的字符,如下图

In [10]: f'your age is {age:^5}'
Out[10]: 'your age is  20  '
In [11]: f'your age is {age:>5}'
Out[11]: 'your age is    20'
In [12]: f'your age is {age:0>5}'
Out[12]: 'your age is 00020'
In [13]: f'your age is {age:2>5}'
Out[13]: 'your age is 22220'
In [14]: f'your age is {age:#>5}'
Out[14]: 'your age is ###20'
In [15]: f'your age is {age:#<5}'
Out[15]: 'your age is 20###'

3. 字符串的format()方法

你可能想看:
« 上一篇
下一篇 »

相关推荐

python爬虫教程PDF,Python爬虫书PDF

2026年09月02日

31阅读

外国教程python,python编程教学视频

2026年09月02日

25阅读

python简明教程沈洁元,python详细基础教程

2026年09月02日

21阅读

python库包教程,python 包

2026年09月02日

26阅读

python教程大全集,python教程600集

2026年09月02日

26阅读

python入门教程完整版,python零基础入门全套教程视频

2026年09月02日

22阅读