品易云推流 关闭
文章详情页
文章 > Python常见问题 > python的format函数怎么用

python的format函数怎么用

format

头像

silencement

2019-12-21 10:21:3921191浏览 · 0收藏 · 0评论

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

python学习网,大量的免费python视频教程,欢迎在线学习!

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

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 = ['python学习网', 'www.py.cn']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

输出结果

网站名:python学习网, 地址 www.py.cn
网站名:python学习网, 地址 www.py.cn
网站名:python学习网, 地址 www.py.cn
关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图