首页 > 文章列表 > Python format函数的用法

Python format函数的用法

Python format
283 2022-08-07

在字符串的时候上,有时候会涉及到格式化的问题。在python的新版本更新中,我们得到了一个新的函数方法format,同时还可以与其他的函数结合使用。下面我们就format函数进行简单说明,然后带来使用方法的介绍。

1、说明

format是python2.6新增的一个格式化字符串的方法,format函数常与print()函数结合使用,具备很强的格式化输出能力。

2、format 函数可以接受不限个参数,位置可以不按顺序。

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

3、使用字典传入,在字典前加入**

grade = {'I' : '拦路雨', '状态': '写博客'}
print('{I}比较无聊,在{状态}'.format(**grade))#字典前加上**