python技巧一

来源:互联网 发布:淘宝上的silkn是真的吗 编辑:程序博客网 时间:2024/06/08 05:22
format函数功能: 2017-9-14
--------------------------------------------------------
它通过{}和:来代替%格式化字符串,“映射”示例
1,通过位置
  1. In [1]: '{0},{1}'.format('kzc',18) 
  1. Out[1]: 'kzc,18'
  1. In [2]: '{},{}'.format('kzc',18) 
  1. Out[2]: 'kzc,18'
  1. In [3]: '{1},{0},{1}'.format('kzc',18) 
  1. Out[3]: '18,kzc,18'

2,通过关键字参数
  1. In [5]: '{name},{age}'.format(age=18,name='kzc') 
  1. Out[5]: 'kzc,18'
3,通过对象属性
  1.  def__init__(self,name,age): 
  1.     self.name,self.age=name,age 
  1.    def__str__(self): 
  1.      return'This guy is {self.name},is {self.age} old'.format(self=self) 
  1. ===========================================================
  1. In [2]: str(Person('kzc',18)) 
  1. Out[2]: 'This guy is kzc,is 18 old'
4,通过下标
  1. In [7]: p=['kzc',18]
  1. In [8]: '{0[0]},{0[1]}'.format(p)
  1. Out[8]: 'kzc,18'
5,转换进制类型
  1. In [54]: '{:b}'.format(17)
  1. Out[54]: '10001'
  1. In [55]: '{:d}'.format(17)
  1. Out[55]: '17'
  1. In [56]: '{:o}'.format(17)
  1. Out[56]: '21'
  1. In [57]: '{:x}'.format(17)
  1. Out[57]: '11'
6,用,号还能用来做金额的千位分隔符
  1. In [47]: '{:,}'.format(1234567890)
  1. Out[47]: '1,234,567,890'
原创粉丝点击