关闭

Python Print的扩展

94人阅读 评论(0) 收藏 举报

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 13511111
3.序列对象的偏移量,很有用
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 t
Note: 值得注意的是,在模板中不能使用负数偏移,但是在外面可以
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)


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:16844次
    • 积分:599
    • 等级:
    • 排名:千里之外
    • 原创:37篇
    • 转载:13篇
    • 译文:2篇
    • 评论:1条