python format用法_python format()用法

转自 https://www.cnblogs.com/gide/p/6955895.html

python2.6开始,新增了一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串。

它通过{}和:来代替%。

#通过位置

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

日期格式也可以使用format

1303036-20190426140436968-1834808057.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值