官方文档
1.若要使用格式化字符串文本,请在开始引号或三重引号之前以f或f开头的字符串。
例子:
year = 2016
event = 'Referendum'
print(f'Results of the {year} {event}')
结果:
Results of the 2016 Referendum
在这里的格式化输出可以是f或者是F开头的,另外对于需要加入输出的相关内容需要用{}括起来。
2.字符串的str.format()方法需要更多的手工操作。您仍然可以使用和标记变量将被替换的位置,并可以提供详细的格式化指令,但您还需要提供要格式化的信息。
str.format():这个是一种需要更多认为操作的格式方法,在{}中就是要替代的位置,不过需要提供相应的格式指令,比如输出类型,精度,位数等等。
例子:
yes_votes = 42_572_654
no_votes = 43_132_495
percentage = yes_votes / (yes_votes + no_votes)
print('{:-9} YES votes {:2.2%}'.format(yes_votes, percentage))
结果如下:
42572654 YES votes 49.67%
另外在str.format()方法中如果“{}”不指定任何的内容,就是按照顺序进行操作
例子:
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
结果:
We are the knights who say "Ni!"
当指定内容时就是按照指定的顺序进行操作的
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
结果:
spam and eggs
eggs and spam
结果会存在一定的差异的。
还有一些情况如下所示:
例子:`
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')
输出结果:
This spam is absolutely horrible.
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
other='Georg')
结果如下所示:
The story of Bill, Manfred, and Georg.
在{}中的内容可以是比较复杂的,多种类型的。
.format()中的内容可以是表达式等。
例子:
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
结果:
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
3.当您不需要花哨的输出,只需要快速显示一些用于调试的变量时,可以使用repr()或str()函数将任何值转换为字符串。
例子:
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print(s)
结果:
The value of x is 32.5, and y is 40000...
直接将数值转化成字符串的形式输出
还有str()的用法
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + str(x) + ', and y is ' + str(y) + '...'
print(s)
结果:
The value of x is 32.5, and y is 40000...
最终的结果是一样的,知识在这里举个栗子。
4.用%也是可以格式化输出的
例子:
import math
print('The value of pi is approximately %5.3f.' % math.pi)
结果:
The value of pi is approximately 3.142.