format是python2.6新增的一个格局化字符串的办法,绝对于老版的%格局办法,它有不少优点。

1.没有需求理睬数据类型的成绩,正在%办法中%s只能代替字符串类型(保举学习:Python视频教程)
2.单个参数能够屡次输入,参数程序能够没有相反
3.填充形式非常灵敏,对齐形式非常弱小
4.民间保举用的形式,%形式将会正在前面的版本被裁汰
format的一个例子
print 'hello {0}'.format('world')输入:
hello world
详细用例:
#经过地位
print '{0},{1}'.format('chuhao',20)
print '{},{}'.format('chuhao',20)
print '{1},{0},{1}'.format('chuhao',20)
#经过要害字参数
print '{name},{age}'.format(age=18,name='chuhao')
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return 'This guy is {self.name},is {self.age} old'.format(self=self)
print str(Person('chuhao',18))
#经过映照 list
a_list = ['chuhao',20,'china']
print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
#my name is chuhao,from china,age is 20
#经过映照 dict
b_dict = {'name':'chuhao','age':20,'province':'shanxi'}
print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
#my name is chuhao, age is 20,from shanxi
#填充与对齐
print '{:>8}'.format('189')
# 189
print '{:0>8}'.format('189')
#00000189
print '{:a>8}'.format('189')
#aaaaa189
#精度与类型f
#保存两位小数
print '{:.2f}'.format(321.33345)
#321.33
#用来做金额的千位分隔符
print '{:,}'.format(1234567890)
#1,234,567,890
#其余类型 次要就是进制了,b、d、o、x辨别是二进制、十进制、八进制、十六进制。
print '{:b}'.format(18) #二进制 10010
print '{:d}'.format(18) #十进制 18
print '{:o}'.format(18) #八进制 22
print '{:x}'.format(18) #十六进制12更多Python相干技巧文章,请拜访Python教程栏目进行学习!
以上就是python里format甚么意义的具体内容,更多请存眷资源魔其它相干文章!
标签: Python python教程 python编程 python使用问题
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!