跳转至

格式化字符串

字符串模版

  • 在字符串前加前缀 fF,通过 {expression} 表达式,可以在字符串中使用表达式的值。
  • 还可在表达式后面增加格式说明符,以便控制内容格式。 ^1662645833279

Python格式化字符串的替代符以及含义

符号 说明
%c 格式化字符及其ASCII码
%s 格式化字符串
%d 格式化整数
%u 格式化无符号整型
%o 格式化无符号八进制数
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同%e,用科学计数法格式化浮点数
%g 根据值的大小决定使用%f或%e
%G 作用同%g,根据值的大小决定使用%f%e
%p 用十六进制数格式化变量的地址
^1662645833287

案例1: 设置浮点数的显示精度

import math
print(f'The value of pi is approximately {math.pi:.3f}.')

print(f'The value of pi is approximately {math.pi:.3f}.')将打印出3.141。在 ':' 后传递整数,为该字段设置最小字符宽度,常用于列对齐。 ^1662682888271

案例2:设置字符换及数字显示长度

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
    print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

f字符串是Python 3.6引入的。如果你使用的是Python 3.5或更早的版本,需要使用format()方法,而非这种f语法。要使用方法format(),可在圆括号内列出要在字符串中使用的变量。对于每个变量,都通过一对花括号来引用。

还可以使用字符串format()方法。str.format() 方法的基本用法如下所示:

for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
^1662682888278

...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

花括号及之内的字符(称为格式字段)被替换为传递给 str.format() 方法的对象。花括号中的数字表示传递给 str.format() 方法的对象所在的位置。

 print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
 print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

str.format() 方法中使用关键字参数名引用值。

print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

最后更新: 2022年10月15日 01:02:48
创建日期: 2022年9月5日 00:56:03
Contributers: yangjh