zoukankan      html  css  js  c++  java
  • 格式化输出

    格式化输出


    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。


    话不多说,上代码说明

    1,format 函数可以接受不限个参数,位置可以不按顺序

    #不设置指定位置,按默认顺序
    >>>"{} {}".format("hello", "world")    
    'hello world'
    
     # 设置指定位置
    >>> "{0} {1}".format("hello", "world")  
    'hello world'
    
     # 设置指定位置
    >>> "{1} {0} {1}".format("hello", "world")  
    'world hello world'
    

    2,也可以设置参数

    >>>print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
     网站名:菜鸟教程, 地址 www.runoob.com
     
    # 通过字典设置参数
    >>>site = {"name": "菜鸟教程", "url": "www.runoob.com"}
    >>>print("网站名:{name}, 地址 {url}".format(**site))
     网站名:菜鸟教程, 地址 www.runoob.com
     
    # 通过列表索引设置参数
    >>>my_list = ['菜鸟教程', 'www.runoob.com']
    >>>print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
    网站名:菜鸟教程, 地址 www.runoob.com
    
    

    3,可以向 str.format() 传入对象

    class AssignValue(object):
        def __init__(self, value):
            self.value = value
    my_value = AssignValue(6)
    print('value 为: {0.value}'.format(my_value))  # "0" 是可选的
    

    输出结果为:

    value 为: 6
    

    4,通过关键字参数

    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)))
    

    输出结果:

    chuhao,18
    This guy is chuhao,is 18 old
    

    5,通过映射 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
    

    6,通过映射 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
    

    7,填充与对齐

    print('{:>8}'.format('189'))
    print('{:0>8}'.format('189'))
    print('{:a>8}'.format('189'))
    

    输出结果:

         189
    00000189
    aaaaa189
    

    8,精度与类型f,保留两位小数

    print('{:.2f}'.format(321.33345))
    

    输出结果:

    321.33
    

    9,用来做金额的千位分隔符

    print('{:,}'.format(1234567890))
    

    输出结果:

    1,234,567,890
    

    10,数字格式化

    print('{:b}'.format(11)) #二进制 1011
    print('{:d}'.format(11))#十进制 11
    print('{:o}'.format(11)) #八进制 13
    print('{:x}'.format(11)) #十六进制B
    print('{:#x}'.format(11))#十六进制0xb
    print('{:#X}'.format(11))#十六进制0xB
    

    forma函数数字格式化更多应用如下表:

    数字 格式 输出 描述
    3.1415926 {:.2f} 3.14 保留小数点后两位
    3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
    -1 {:+.2f} -1.00 带符号保留小数点后两位
    2.71828 {:.0f} 3 不带小数
    5 {:0>2d} 05v 数字补零 (填充左边, 宽度为2)
    5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
    10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
    1000000 {:,} 1,000,000 以逗号分隔的数字格式
    0.25 {:.2%} 25.00% 百分比格式
    1000000000 {:.2e} 1.00e+09 指数记法
    13 {:10d} 13 右对齐 (默认, 宽度为10)
    13 {:<10d} 13 左对齐 (宽度为10)
    13 {:^10d} 13 中间对齐 (宽度为10)
    如有问题可联系QQ:2499578824
  • 相关阅读:
    70.BOM
    69.捕获错误try catch
    68.键盘事件
    523. Continuous Subarray Sum
    901. Online Stock Span
    547. Friend Circles
    162. Find Peak Element
    1008. Construct Binary Search Tree from Preorder Traversal
    889. Construct Binary Tree from Preorder and Postorder Traversal
    106. Construct Binary Tree from Inorder and Postorder Traversal
  • 原文地址:https://www.cnblogs.com/chunbo/p/11187831.html
Copyright © 2011-2022 走看看