输出格式美化
Python两种输出值的方式:表达式语句和print()函数
第三种放啊是是使用文件对象write()方法,标准输出文件可以用sys.stdout引用
str.format()函数可以格式化输出值(使输出的形式更加多样)
repr()或str()函数可以将输出值转成字符串
str():函数返回一个用户易读的表达形式
repr():产生一个解释器易读的表达形式
s='Hello World'
print(str(s))
#repr()函数可以转义字符串中的特殊字符
print(repr(s))
print(str(1/7))
x=10*3.25
y=200*200
s='x的值为:'+repr(x)+',y的值为:'+repr(y)+"..."
print(s)
hello='hello,world\n'
print(repr(hello))
#repr()的参数可以是Python的任何对象
print(repr((x,y,('Google','Baidu'))))
案例
#第一种方式:
for x in range(1,11):
print(repr(x).rjust(2),repr(x*x).rjust(3),end=" ")
#注意前一行end的使用
print(repr(x*x*x).rjust(4))
#第二种方式:
for x in range(1,11):
print('{0:2d}{1:3d}{2:4d}'.format(x,x*x,x*x*x))
结果:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
101001000