python中format函数如何使用

2020-10-08 0 209
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.jb51.net']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

输出结果

网站名:自学编程网, 地址 www.jb51.net
网站名:自学编程网, 地址 www.jb51.net
网站名:自学编程网, 地址 www.jb51.net

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

遇见资源网 Python python中format函数如何使用 http://www.ox520.com/26209.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务