python如何打印字符串_python 中 打印及格式化字符串的相关方法
将值转换为字符串
Python 有多种方式将任何值转为字符串: 将它传给 repr() 或 str() 函数.
repr() 和 str() 的区别,看几个例子:
>>> print(str('123'))
123
>>> print(str(123))
123
>>> print(repr('123'))
'123'
>>> print(repr(123))
123
再看这个例子
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(str(now))
2017-04-22 15:41:33.012917
>>> print(repr(now))
datetime.datetime(2017, 4, 22, 15, 41, 33, 12917)
因此 str() 与 repr() 的不同在于:
str() 的输出追求可读性,输出格式要便于理解,适合用于输出内容到用户终端。
repr() 的输出追求明确性,除了对象内容,还需要展示出对象的数据类型信息,适合开发和调试阶段使用。
str.format 的使用
括号及其里面的字符 (称作 format field) 将会被 format() 中的参数替换. 在括号中的数字用于指向传入对象在 format() 中的位置.
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数.
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
可选项 ':' 和格式标识符可以跟着 field name. 这就允许对值进行更好的格式化. 下面的例子将 Pi 保留到小数点后三位.
>>> import math
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.
'!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr()) 可以用于在格式化某个值之前对其进行转化:
>>> import math
>>> print('The value of PI is approximately {}.'.format(math.pi))
The value of PI is approximately 3.14159265359.
>>> print('The value of PI is approximately {!r}.'.format(math.pi))
The value of PI is approximately 3.141592653589793.
格式化字典,使用 **
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
旧式字符串格式化
使用 %进行字符串格式化
>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.