网络编程
位置:首页>> 网络编程>> Python编程>> python中format函数如何使用

python中format函数如何使用

作者:silencement  发布时间:2022-06-18 06:50:41 

标签: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

来源:https://www.py.cn/faq/python/12584.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com