我是靠谱客的博主 专注睫毛,这篇文章主要介绍python中format函数什么意思,现在分享给大家,希望可以做个参考。

python中format函数什么意思?

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

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

推荐:《Python教程》

实例

复制代码
1
2
3
4
5
6
7
8
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'
登录后复制

也可以设置参数:

实例

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python # -*- coding: UTF-8 -*- print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com")) # 通过字典设置参数 site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['菜鸟教程', 'www.runoob.com'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
登录后复制

输出结果为:

复制代码
1
2
3
网站名:菜鸟教程, 地址 www.runoob.com 网站名:菜鸟教程, 地址 www.runoob.com 网站名:菜鸟教程, 地址 www.runoob.com
登录后复制

也可以向 str.format() 传入对象:

实例

复制代码
1
2
3
4
5
6
7
8
#!/usr/bin/python # -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
登录后复制

输出结果为:

复制代码
1
value 为: 6
登录后复制

以上就是python中format函数什么意思的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是专注睫毛最近收集整理的关于python中format函数什么意思的全部内容,更多相关python中format函数什么意思内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(85)

评论列表共有 0 条评论

立即
投稿
返回
顶部