输入与输出--格式化输出

str()与repr()

对于字符串:两方法作用结果有差异
对于列表,元组,字典等:两方法输出一致

s="hello\n"
print(str(s))
print(repr(s))
a=[1,2,3,4]
print(str(a))
print(repr(a))

输出:
hello

‘hello\n’
[1, 2, 3, 4]
[1, 2, 3, 4]

平方与立方表 打印的两种方法

for x in range(1,11):
    print(repr(x).rjust(2),repr(x**2).rjust(3),end=" ")
    print(repr(x**3).rjust(4))
for x in range(1,11):
    print("{0:2d} {1:3d} {2:4d}".format(x,x**2,x**3))

输出:
输入与输出--格式化输出_第1张图片

右对齐,左对齐,居中

print("hello")
print("hello".rjust(10))         #str.rjust()
print("hello".ljust(10))         #str.ljust()
print("hello".center(10))        #str.center()

输出:
在这里插入图片描述

str2=“hello”.rjust(10)[:10]

str.zfill()

左侧补零

print("11".zfill(10))             #str.zfill()  左侧补零,输出:0000000011

str.format()

print("hello,{} am {}".format("I","Jack"))       #输出:hello,I am Jack

括号中数字代表参数位置

print("{0} {1}".format("hello ","world "))      #输出:hello  world
print("{1} {0}".format("hello ","world "))      #输出:world  hello

关键字参数

print("the {obj} is {adr}".format(obj="weather",adr="sunny"))     #输出:the weather is sunny

位置参数和关键字参数混合

#输出:the weather is sunny,I am happy today!
print("the {obj} is {adr},{0}".format("I am happy today!",obj="weather",adr="sunny"))   

’!a’,’!s’,’!r’分别运用ascii(),str(),repr()转换格式

s="hello"
print("say {}".format(s))
print("say {!a}".format(s))
print("say {!r}".format(s))
print("say {!s}".format(s))

输出:
输入与输出--格式化输出_第2张图片

冒号后设置格式

import math
print("approximate value of pi: {0:.3f}".format(math.pi))     #小数位为3位
print("approximate value of pi: {0:10.3f}".format(math.pi))    #10设置的是总长度
print("approximate value of pi: {0:10d}".format(5))          #d整数

输出:
在这里插入图片描述

字典的两种处理方式:后一种运算快

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]}; Sjoerd: {0[Sjoerd]}; '
        'Dcab: {0[Dcab]}'.format(table))

输出:
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

print('Jack: {Jack}; Sjoerd: {Sjoerd}; Dcab: {Dcab}'.format(**table))

输出:
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

旧版本的格式化输出

import math
print("approximate value of pi: %.3f"%(math.pi))

你可能感兴趣的:(python)