1,打印字符串(str),利用%s
。
>>> print ('My name is %s' % ('TaoXiao'))
My name is TaoXiao
- 1
- 2
- 3
2,打印整数,浮点数。
>>> print ("He is %d years old" % (23)) # 整数 %d
He is 23 years old
>>> print ("His height is %f m" % (1.73)) # 浮点数 %f
His height is 1.730000 m
>>> print ("His height is %.2f m" %(1.73)) # 浮点数(指定保留小数点位数) %.2f
His height is 1.73 m
>>> print ("His height is %.4f m" %(1.73)) # 浮点数(强制保留4位) %.4f
His height is 1.7300 m
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
3,利用format。这是官方推荐用的方式,%方式将可能在后面的版本被淘汰。
>>> print('{1},{0},{1}'.format('TaoXiao',18)) # 通过位置传递,相当方便,可以重复,可以换位置。
18,TaoXiao,18
>>> print('{name}: {age}'.format(age=24,name='TaoXiao')) # 通过关键字传递
TaoXiao: 24
- 1
- 2
- 3
- 4
- 5
- 6
format还有其他很多用法。可以点击这里。