zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Python] format格式化函数

Python 函数 格式化 format
2023-09-11 14:22:54 时间

格式化字符串函数 str.format()

format函数可以接受无限个参数,位置可以不按顺序

'{} {}'.format('Hello','World') # 不设置指定位置,按默认顺序 
# 'Hello World' 
'{0} {1}'.format('Hello','World') # 设置指定位置 
# 'Hello World' 
'{1} {0} {1}'.format('Hello','World') # 设置指定位置 
# 'World Hello World'

也可以设置参数:

# 网站名:CSDN, 地址 https://www.csdn.net
print("网站名:{name}, 地址 {url}".format(name="CSDN", url="https://www.csdn.net"))

# 通过字典设置参数 
site = {"name": "CSDN", "url": "https://www.csdn.net"} 
print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数 
my_list = ['CSDN', 'https://www.csdn.net'] 
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

可以使用大括号{}来转义大括号,如下实例:

print ("{} 对应的位置是 {{0}}".format("runoob")) # runoob 对应的位置是 {0}