python中format函数如何使用
作者:silencement 时间:2022-06-18 06:50:41
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 = ['脚本之家', 'www.jb51.net']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的
输出结果
网站名:脚本之家, 地址 www.jb51.net
网站名:脚本之家, 地址 www.jb51.net
网站名:脚本之家, 地址 www.jb51.net
来源:https://www.py.cn/faq/python/12584.html
标签:python,format函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
让IE6更快的走向灭亡
2010-02-03 15:05:00
![](https://img.aspxhome.com/file/UploadPic/20102/3/ie6rip-37s.jpg)
各种Python库安装包下载地址与安装过程详细介绍(Windows版)
2021-01-27 14:00:05
![](https://img.aspxhome.com/file/2023/9/89089_0s.png)
css行高:line-height属性详解
2008-06-24 11:42:00
![](https://img.aspxhome.com/file/UploadPic/20086/24/2008624115434297s.gif)
Python requests的SSL证书验证方式
2021-10-06 09:21:51
![](https://img.aspxhome.com/file/2023/8/118058_0s.png)
Python搜索引擎实现原理和方法
2023-06-26 05:35:32
![](https://img.aspxhome.com/file/2023/7/67327_0s.png)
Python Json数据文件操作原理解析
2022-10-27 19:00:32
![](https://img.aspxhome.com/file/2023/6/81556_0s.png)
Python使用urllib2模块实现断点续传下载的方法
2021-12-27 05:20:01
如何创建SQL Server 2000故障转移群集
2009-02-13 17:18:00
Dreamweaver制作技巧四则
2008-01-04 09:42:00
Python中断多重循环的几种方式详解
2022-05-09 21:44:04
Python数据可视化实现正态分布(高斯分布)
2022-10-28 03:31:29
![](https://img.aspxhome.com/file/2023/0/87780_0s.jpg)
Python OpenCV实现姿态识别的详细代码
2023-05-27 23:42:31
![](https://img.aspxhome.com/file/2023/9/78719_0s.jpg)
Python try-except-else-finally的具体使用
2022-10-18 14:31:45
![](https://img.aspxhome.com/file/2023/3/115643_0s.png)
Python+AutoIt实现界面工具开发过程详解
2023-06-17 20:39:47
![](https://img.aspxhome.com/file/2023/1/99301_0s.png)
js实现登录注册框手机号和验证码校验(前端部分)
2023-09-13 02:41:37
Python实现数据集划分(训练集和测试集)
2022-11-29 23:54:11
python实现从pdf文件中提取文本,并自动翻译的方法
2021-06-08 18:55:56
![](https://img.aspxhome.com/file/2023/5/84135_0s.jpg)
你是真正的用户体验设计者吗? Ⅰ
2008-03-20 13:42:00
Python通过TensorFlow卷积神经网络实现猫狗识别
2023-09-29 10:59:56
Python实现为PDF去除水印的示例代码
2023-03-05 04:27:56