python中format函数怎样使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python中format函数怎样使用

silencement   2020-06-22 我要评论

在这篇文章中小编为您整理的是一篇关于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 = ['', 'www.qb5200.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果

网站名:, 地址 www.qb5200.com
网站名:, 地址 www.qb5200.com
网站名:, 地址 www.qb5200.com

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们