-
位置:需要严格控制入参的位置
'{0} {1}'.format("Hello", "XingZhe")
-- > 'Hello XingZhe'
'{0}_{0}'.format("Hello", "XingZhe")
-- > 'Hello_Hello'
'{}_{}'.format("Hello", "XingZhe”)
-- > 'Hello_XingZhe'
'{1} {0} {1}'.format('Hello','XingZhe')
-- > 'XingZhe Hello XingZhe'
-
关键字:代码可读性强;插入多个值只需传入1个参数;
'I am {name}, age is {age}'.format(name = 'XingZhe', age = '29')
-- > 'I am XingZhe, age is 29'
-
列表
list1 = ['world','python']
'Hello {names[0]}, I am {names[1]}'.format(names = list1)
-- > 'Hello world, I am python'
'Hello {0[0]}, I am {0[1]}'.format(list1)
-- > 'Hello world, I am python'
-
字典:访问字典的key,不需要引号,
format()
的参数加星号表示模糊映射;
site = {"name":"菜鸟教程", "url":"[www.runoob.com](http://www.runoob.com)"}
"Hello {domain[name]}, I am {domain[url]}".format(domain = site)
-- > 'Hello 菜鸟教程, I am [www.runoob.com](http://www.runoob.com)'
"Hello {name}, I am {url}".format(**site)
-- > 'Hello 菜鸟教程, I am [www.runoob.com](http://www.runoob.com)'
-
类
class Sentence:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'The boy is {self.name}, age is {self.age} old'.format(self=self)
print(Sentence('XZ', 29))
-- > The boy is XZ, age is 29 old
-
下标
names = ["xiaoming", "xiaoli","xiaohong"]
ages = [28,16,9]
"The bos is {0[2]}, age is {1[1]}".format(names,ages)
-- > 'The bos is xiaohong, age is 16'