format函数在python中的应用

这篇文章将为大家详细讲解有关format函数在python中的应用,文章内容质量较高,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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" 是必须的

也可以向 str.format() 传入对象:

#!/usr/bin/python# -*- coding: UTF-8 -*- class AssignValue(object):    def __init__(self, value):        self.value = valuemy_value = AssignValue(6)print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

输出结果为:

value 为: 6

以上就是format函数在python中的应用,看完之后是否有所收获呢?如果想了解更多相关内容,欢迎关注行业资讯,感谢各位的阅读。