python3 print和format函数

print函数

  • 输出字符串和数字(,)
>>>usd_voalue=98/6.77
>>>print("美元转换成人民币金额是:",usd_voalue)
14.18
>>>L=[1,2,'hello world']
>>>print(L)
[1,2,'hello world']
  • 格式化输出(%)
>>>str = "the length of (%s) is %d" %('runoob',len('runoob'))
>>> print(str)
the length of runoob is 6
# 格式化输出浮点数
>>> print('%010.3f' % pi) #用0填充空白  ,-:左对齐
000003.142 
# 自动换行
#默认为自动换行
>>>for i in range(0,5):
...     print(i )
0
1
2
3
4
#非自动换行
>>>for i in range(0,5):
...     print(i, end = '' )
01234

format函数(.)

str.format(),其中通过 {} 和 : 来代替以前的 %

# 不设置参数
>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
# 设置指定位置
>>> "{1} {0} {1}".format("hello", "world") 
'world hello world'
# 设置变量参数
>>>print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
网站名:菜鸟教程, 地址 www.runoob.com
#设置字典参数
>>>site = {"name": "菜鸟教程", "url": "www.runoob.com"}
>>>print("网站名:{name}, 地址 {url}".format(**site))
网站名:菜鸟教程, 地址 www.runoob.com
#设置列表索引参数
>>>my_list = ['菜鸟教程', 'www.runoob.com']
>>>print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
网站名:菜鸟教程, 地址 www.runoob.com
# 数字格式化
>>> print("{:.2f}".format(3.14159));
3.14

猜你喜欢

转载自blog.csdn.net/Amy8020/article/details/88814005