zoukankan      html  css  js  c++  java
  • python中强大的format函数

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

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

    请看下面的示例,基本上总结了format函数在python的中所有用法

     1 #通过位置
     2 print '{0},{1}'.format('chuhao',20)
     3 
     4 print '{},{}'.format('chuhao',20)
     5 
     6 print '{1},{0},{1}'.format('chuhao',20)
     7 
     8 #通过关键字参数
     9 print '{name},{age}'.format(age=18,name='chuhao')
    10 
    11 class Person:
    12     def __init__(self,name,age):
    13         self.name = name
    14         self.age = age
    15 
    16     def __str__(self):
    17         return 'This guy is {self.name},is {self.age} old'.format(self=self)
    18 
    19 print str(Person('chuhao',18))
    20 
    21 #通过映射 list
    22 a_list = ['chuhao',20,'china']
    23 print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
    24 #my name is chuhao,from china,age is 20
    25 
    26 #通过映射 dict
    27 b_dict = {'name':'chuhao','age':20,'province':'shanxi'}
    28 print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
    29 #my name is chuhao, age is 20,from shanxi
    30 
    31 #填充与对齐
    32 print '{:>8}'.format('189')
    33 #     189
    34 print '{:0>8}'.format('189')
    35 #00000189
    36 print '{:a>8}'.format('189')
    37 #aaaaa189
    38 
    39 #精度与类型f
    40 #保留两位小数
    41 print '{:.2f}'.format(321.33345)
    42 #321.33
    43 
    44 #用来做金额的千位分隔符
    45 print '{:,}'.format(1234567890)
    46 #1,234,567,890
    47 
    48 #其他类型 主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。
    49 
    50 print '{:b}'.format(18) #二进制 10010
    51 print '{:d}'.format(18) #十进制 18
    52 print '{:o}'.format(18) #八进制 22
    53 print '{:x}'.format(18) #十六进制12

    --End

  • 相关阅读:
    10003 Cutting Sticks(区间dp)
    Cocos2d-x init() 和 onEnter() 区别
    HDU1181【有向图的传递闭包】
    空间参考系统与WKT解析
    面试经典-分金条
    uvalive 3971
    lua学习:使用Lua处理游戏数据
    面试经典--两个房间 每间房间三盏灯
    浙江大学PAT上机题解析之2-11. 两个有序链表序列的合并
    顺序队列之C++实现
  • 原文地址:https://www.cnblogs.com/gide/p/6955895.html
Copyright © 2011-2022 走看看