Python输入和输出
格式化输出:
print()
write()
sys.stdout
值转化成字符串:
repr():
转化为供解释器读取的形式
str():
转换为供人读取的形式
#将字符串输出到一列,并向左侧填充空格以右对齐,同理还有str.ljust,str.center()
str.rjust()
#向数值的字符串表达式填充0
>>> '12'.zfill(5)
'00012'
#.format基础用法‘{}’占位
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
#关键字参数
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
#位置参数和关键字参数可以随意组合
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))
#'!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.
# {:} ':' 指令允许对值的格式化加以控制
>>> import math
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
#对较长的字符串用命名引用
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table))
#%格式化法
>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
#>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!"