format()函数式增强了字符串的格式化功能,使用形式是 str.format()。format由两个部分组成,字符串模板和模板数据内容组成,通过大括号{},将模板数据内容嵌到字符串模板对应的位置。
template = 'hello {}' #字符串模板
world = 'world' #模板数据内容
result = template.format(world)
print(result)
输出结果:
hello world
需要格式化多个内容时,可以指定顺序
template = 'hello {0},hello {1},hello {2}'
result = template.format('world','python','shanghai')
print(result)
输出结果:
hello world,hello python,hello shanghai
格式化多个内容时,可以随意指定顺序
template = 'hello {1},hello {0},hello {2}'
result = template.format('world', 'python', 'shanghai')
print(result)
输出结果:
hello python,hello world,hello shanghai
也可以通过指定对应的名字
template = 'hello {w},hello {p},hello {s}'
result = template.format(w='world',s='shanghai',p='python')
print(result)
输出结果:
hello world,hello python,hello shanghai
本文介绍Python中使用format()函数进行字符串格式化的多种方法,包括如何指定数据插入位置及使用名称来匹配数据。
5281

被折叠的 条评论
为什么被折叠?



