python中format函数用法简书_python format 函数总结

python format 函数总结

文章基于Python2.7.12进行讲述:

在python中格式化字符串进行输出时,通常会用到format函数。

介绍一下简单用法:

1.将字符串替换

In [1]: print '{0} {1} {2}'.format('a', 'b', 'c')

a b c

2.按照参数格式化

In [2]: print '{name} {age}'.format(age=21, name='lkhardy')

lkhardy 21

3.限制字符串内的信息范围

In [3]: print '{array[5]}'.format(array=range(10))

5

In [4]: print '{array[12]}'.format(array=range(10))

-------------------------------------IndexError

Traceback (most recent call last)

in ()---->

1 print '{array[12]}'.format(array=range(10))

IndexError: list index out of range

4.直接调用系统函数

In [14]: print '{attr.__class__}'.format(attr=0)

In [15]: print '{attr.__class__}'.format(attr="d")

5.转义

In [18]: print '{name!r}'.format(name=u'汉字')

u'\u6c49\u5b57'

In [19]: print '{name!r}'.format(name=u'lkhardy')

u'lkhardy'

In [20]: print '{name!r}'.format(name=u'1234')

u'1234'

6.识别格式化

In [24]: print '{digit:*^ 10.5f}'.format(digit=1.0/3)

* 0.33333*

In [25]: print '{digit:*^ 10.5f}'.format(digit=10.0/3)

* 3.33333*

未完待续。。。。。。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值