对于字符串:两方法作用结果有差异
对于列表,元组,字典等:两方法输出一致
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))
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]
左侧补零
print("11".zfill(10)) #str.zfill() 左侧补零,输出:0000000011
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))
冒号后设置格式
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))