导读:
Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。超级自由和超级爽!
原来我们用%百分号格式化输出,现在你可以通过format函数替代老土的% 方法,哈哈
用法介绍:
{} 表示输出的个数
:可以控制,冒号前面表示索引下标,冒号后面表示添加条件限制,比如宽度
1、控制输出个数
a="{}".format("hello", "world")
print(a)
a="{}{}".format("hello", "world")
print(a)
a="{} {}".format("hello", "world") # {}之间的空格也决定输出两个元素的空格
print(a)
输出:
hello
helloworld
hello world
常见错误:
a="{}{}{}".format("hello", "world")
print(a)
报错IndexError: tuple inde