Python format() 基础

Python format() 高级。

 

format格式化

# ^,<,>分别表示居中,左对齐,右对齐;冒号后面是要填充的字符,只能是一个字符,不指定默认为空格
print('{:*^60}'.format('token & word mapping review:'))

 

print('{:.2f}'.format(3.1415926))
# 使用大括号{}转义大括号
print('{}对应的位置是:{{0}}'.format('runoob'))
runoob对应的位置是:{0}

 

format函数接受不限个参数,位置不按顺序

print('{}{}'.format('hello', 'world'))    # 不设定位置,默认按顺序
print('{0},{1}'.format('hello', 'world'))  # 设定顺序
print('{1}-{0}-{1}'.format('hello', 'world'))
helloworld
hello,world
world-hello-world

format设置参数

print('网站名:{name}, 地址{url}'.format(name='菜鸟教程',url='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’是必须的。

 

posted @ 2018-07-02 10:03  做梦当财神  阅读(278)  评论(0编辑  收藏  举报