python中format函数如何使用

Ilona ·
更新时间:2024-09-20
· 855 次阅读

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中强大的format函数实例详解Python中用format函数格式化字符串的用法



format format函数 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号