字符串格式化 | 周末学习

本文已参与周末学习计划,点击链接查看详情:周末学习

1. 使用 % 操作符

在 Python 中,要实现格式化字符串,可以使用 % 操作符,其模板格式如下:

‘%[-][+][0][m][.n]type’ % exp

例如,格式化输出一个保存用户信息的字符串,代码如下:

# -*- coding:utf-8 -*-

# 定义模板,%s 表示格式化字符串,%06d 表示格式化十进制整数,宽度为 6 个字符,以 0 占位
template = "用户名: %s\t用户 UID: %06d"

print(template % ("fiz", 6))
print(template % ("Q", 378930))
复制代码

执行效果如下:

用户名: fiz     用户 UID: 000006
用户名: Q  用户 UID: 378930
复制代码

但是,由于使用 % 操作符是早期 Python 提供的方法,自从 Python 2.6 版本开始,字符串对象提供了 format() 方法对字符串进行格式化。现在一些 Python 社区也推荐使用这种方法,所以我们把重点放在后面。

2. 使用字符串对象的 format() 方法

字符串对象提供了 format() 方法用于进行字符串格式化,语法格式如下:

string.format(*args)

下面重点介绍创建模板。在创建模板时,需要使用 {} 和 : 指定占位符。占位符语法格式如下:

{[index][:[[fill]align][sign][#][width][.precision][type]]}
复制代码

注意!当一个模板中,出现多个占位符时,指定索引位置的规范须统一,即全部采用手动指定或自动指定。例如,定义 ‘我是数值:{:d},我是字符串:{1:s}’ 模板是错误的,会抛出 ValueError 异常。

还是以输出一个保存用户信息的字符串为例子,代码如下:

# -*- coding:utf-8 -*-

# 定义字符串模板
# {:s}    表示格式化字符串
# {:0>6d} 表示格式化字符串,右对齐,宽度为 6,以 0 填充空白处
template = "用户名:{:s}\t用户UID:{:0>6s}"

# 格式化字符串并输出
print(template.format('fiz', '9'))
print(template.format('Q', '378930'))
复制代码

执行效果如下:

用户名:fiz       用户UID:000009
用户名:Q    用户UID:378930
复制代码

3. 使用 f-string

f-string 用大括号 {} 表示被替换字段,其中直接填入替换内容:

>>> name = 'Eric'
>>> f'Hello, my name is {name}'
'Hello, my name is Eric'

>>> number = 7
>>> f'My lucky number is {number}'
'My lucky number is 7'

>>> price = 19.99
>>> f'The price of this book is {price}'
'The price of this book is 19.99'
复制代码

表达式求值与函数调用
f-string 的大括号 {} 可以填入表达式或调用函数,Python 会求出其结果并填入返回的字符串内:

>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'

>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'

>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'

>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享