python中format函数如何使用

在本篇内容里小编给大家整理的是一篇关于python的format函数用法以及相关实例,需要的朋友们学习下。

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

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

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

例如

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

也可设置参数

 #!/usr/bin/python # -*- coding: UTF-8 -*- print("网站名:{name}, 地址 {url}".format(name="python学习网", url="www.py.cn")) # 通过字典设置参数 site = {"name": "python学习网", "url": "www.py.cn"} print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['html中文网', 'www.0133.cn'] print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果

网站名:html中文网, 地址 www.0133.cn
网站名:html中文网, 地址 www.0133.cn
网站名:html中文网, 地址 www.0133.cn

到此这篇关于python中format函数如何使用的文章就介绍到这了,更多相关python的format函数用法内容请搜索html中文网以前的文章或继续浏览下面的相关文章希望大家以后多多支持html中文网!

以上就是python中format函数如何使用的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python