在实际开发中我们希望输出的内容或用于日志排查或用于SQL拼接或用于组织数据结构;那么在Python中我们就需要熟悉1、格式化字符串字面值2、字符串format()方法 输出格式;
平时接触的输出方式:
1.表达式语句
result = x + y * 2
2.print()函数
3.文件对象的write()方法
格式化字符串字面值
使用 格式化字符串字面值 ,要在字符串开头的引号/三引号前添加 f 或 F 。在这种字符串中,可以在 { 和 } 字符之
间输入引用的变量,或字面值的 Python 表达式。
year = 2016
event = 'chinese'
F'Results of the {year} {event}'
如果不需要花哨的输出,只想快速显示变量进行调试,可以用 repr() 或 str() 函数把值转化为字符串。
str() 函数返回供人阅读的值,repr() 则生成适于解释器读取的值(如果没有等效的语法,则强制执行 SyntaxError)。对于没有支持供人阅读展示结果的对象, str() 返回与 repr() 相同的值。一般情况下,数字、列表或字典等结构的值,使用这两个函数输出的表现形式是一样的。字符串有两种不同的表现形式。
s = 'Hello, world.'
str(s)
repr(s)
str(1/7)
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print(s)
hello = 'hello, world\n'
hellos = repr(hello)
print(hellos)
repr((x, y, ('spam', 'eggs')))
- 格式化字符串字面值 (简称为 f-字符串)在字符串前加前缀 f 或 F,通过 {expression} 表达式,把 Python 表达式的值添加到字符串内。
import math
print(f'The value of pi is approximately {math.pi:.9f}.')
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 76718}
for name, phone in table.items():
print(f'{name:8} ==> {phone:8d}')
- 还有一些修饰符可以在格式化前转换值。 ‘!a’ 应用 ascii() ,‘!s’ 应用 str(),‘!r’ 应用 repr():
animals = 'eels'
print(f'My hovercraft is full of {animals}.')
print(f'My hovercraft is full of {animals !a}.')
print(f'My hovercraft is full of {animals !s}.')
print(f'My hovercraft is full of {animals!r}.')
字符串 format() 方法
str.format() 方法的基本用法如下所示:
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
1.str.format() 方法中使用数字表示传递对象所在的位置。
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
2.str.format() 方法中使用关键字参数名引用值。
print('This {food} is {adjective}.'.format(
food='spam', adjective='absolutely horrible'))
3.str.format() 方法位置参数和关键字参数可以任意组合:
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))
4.str.format() 方法传递字典,并用方括号 ‘[]’ 访问键来完成。
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
'Dcab: {0[Dcab]:d}'.format(table))
也可以用 ‘**’ 符号,把 table 当作传递的关键字参数。
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
5.扩展:内置函数 vars() 结合使用时,这种方式非常实用,可以返回包含所有局部变量的字典。
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))