Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 python里format什么意思

python里format什么意思

发布时间:2020-11-11   编辑:www.jquerycn.cn
jquery中文网为您提供python里format什么意思等资源,欢迎您收藏本站,我们将为您提供最新的python里format什么意思资源
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什么意思的详细内容,更多请关注jquery中文网其它相关文章!

  • 本文原创发布jQuery中文网,转载请注明出处,感谢您的尊重!
  • 您可能感兴趣的文章:
    python里format什么意思
    python中format函数什么意思
    python中f是什么
    python怎么用百分数
    python中r代表什么意思
    python setup.py install是什么意思
    python里//什么意思
    r在python中表示什么意思
    python正则表达式r表示什么意思
    python里len什么意思

    [关闭]