1.将Format后面的内容以此填充
print "I am {0}, and I like {1}".format('Sharon', 'Python')
2.用关键词来指明所应该填充的内容
print "I am {name}, I like {all}, this is my tel {0}".format(13511111,name='Sharon', all=['Python','Java','C#','C'])返回:I am Sharon, I like ['Python', 'Java', 'C#', 'C'], this is my tel 135111113.序列对象的偏移量,很有用print "First char of word {0} is {0[0]}, Second char is {0[2]}".format('Python')返回:First char of word Python is P, Second char is tNote: 值得注意的是,在模板中不能使用负数偏移,但是在外面可以print "First char of word {0} is {0[-1]}, Second char is {0[2]}".format('Python')print "First char of word {0} is {0[-1]}, Second char is {0[2]}".format('Python') TypeError: string indices must be integers, not str放在外面:word = 'Hello' print "First char is {0}, second char is {1}".format(word[0],word[1])
4. 除了根据位置得到,还能根据Dictionary的key得到,
infoDic={'name':'Sharon', 'qq':18209548, 'tel':13511111} template='My name is {myinfoDic[name]}, my QQ is {myinfoDic[qq]}' print template.format(myinfoDic=infoDic)