要使用 格式化字符串字面值 ,请在字符串的开始引号或三引号之前加上一个 f 或 F 。在此字符串中,你可以在 { 和 } 字符之间写可以引用的变量或字面值的 Python 表达式。
1 2 3 4 5 6 7 8
>>> >>> year = 2016 >>> event = 'Referendum' >>> f'Results of the {year}{event}' 'Results of the 2016 Referendum' >>> import math >>> print(f'The value of pi is approximately {math.pi:.3f}.') The value of pi is approximately 3.142.
>>> s = 'Hello, world.' >>> str(s) 'Hello, world.' >>> repr(s) "'Hello, world.'" >>> str(1/7) '0.14285714285714285' >>> 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 is32.5, and y is40000... >>> # The repr() of a string adds string quotes and backslashes: ... hello = 'hello, world\n' >>> hellos = repr(hello) >>> print(hellos) 'hello, world\n' >>> # The argument to repr() may be any Python object: ... repr((x, y, ('spam', 'eggs'))) "(32.5, 40000, ('spam', 'eggs'))"
format
str.format() 方法的基本用法如下所示:
1 2 3
>>> >>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!"