首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python中format所有用法

python中format所有用法

作者头像
全栈程序员站长
发布2022-09-06 18:28:01
发布2022-09-06 18:28:01
5190
举报

大家好,又见面了,我是你们的朋友全栈君。

平时只用参数匹配,偶尔看到别人的format用法楞住没反应过来,遂记下

代码语言:javascript
复制
#通过位置
print '{0},{1}'.format('hehe',20)

print '{},{}'.format('hehe',20)

print '{1},{0},{1}'.format('hehe',20)

#通过关键字参数
print '{name},{age}'.format(age=18,name='hehe')

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('hehe',18))

#通过映射 list
a_list = ['hehe,20,'china']
print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
#my name is hehe,from china,age is 20

#通过映射 dict
b_dict = {'name':'hehe','age':20,'province':'shanxi'}
print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
#my name is hehe, 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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/155850.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 平时只用参数匹配,偶尔看到别人的format用法楞住没反应过来,遂记下
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档