zoukankan      html  css  js  c++  java
  • Python:format()方法

     转于:https://blog.csdn.net/zhang89xiao/article/details/53818906

    博主:张肖的博客

    描述:

    format的格式

    replacement_field     ::=  “{” [field_name] [“!” conversion] [“:” format_spec] “}”
    field_name              ::=      arg_name (“.” attribute_name | “[” element_index “]”)*
    arg_name               ::=      [identifier | integer]
    attribute_name       ::=      identifier
    element_index        ::=      integer | index_string
    index_string           ::=      <any source character except “]”> +
    conversion              ::=      “r” | “s” | “a”
    format_spec            ::=      <described in the next section>

    format_spec 的格式

    format_spec   ::=    [[fill]align][sign][#][0][width][,][.precision][type]

    fill             ::=    <any character>
    align           ::=    ”<” | “>” | “=” | “^”
    sign            ::=    ”+” | “-” | ” “
    width           ::=    integer
    precision       ::=    integer
    type            ::=    ”b” | “c” | “d” | “e” | “E” | “f” | “F” | “g” | “G” | “n” | “o” | “s” | “x” | “X” | “%”

    功能:共4个功能

    一)填充字符串

    #只能用{ }来放标签

    A、通过位置填充字符串:{0},表示format的左起第一个元素;

    print('hello {0} i am {1}, {1} love {0}'.format('MM', 'GG'))
    #输出:hello MM i am GG, GG love MM

    B、通过key来填充

    print('hello {0} i am {g}, {g} love {0}'.format('MM', g = 'GG'))
    #输出:hello MM i am GG, GG love MM

    C、通过下标填充

    #format的参数,当'I', names = names, u = 'U',三种混用是,'I'类型放最前;

    names = ['MM', 'GG']
    print('hello {names[0]}, i am {names[1]}, {0} love {u}'.format('I', names = names, u = 'U'))
    #输出:hello MM i am GG, I love U

    D、通过字典的key填充

    names = {'m':'MM', 'g':'GG'}
    print('hello {names[m]} i am {names[g]}, {i} love {u}'.format(names = names, i = 'I',u = 'U'))
    #输出:hello MM i am GG, I love U

    E、通过对象的属性填充

    class Names():
        m = 'MM'
        g = 'GG'
    
    print('hello {names.m}, i am {names.g}'.format(names = Names))
    #输出:hello MM, i am GG

    F、使用魔法参数填充

    args = ['I', 'U']
    kwargs = {'m':'MM', 'g':'GG'}
    print('hello {m} , i am {g}, {} love {}'.format(*args, **kwargs))
    #输出:hello MM , i am GG, I love U

    二)格式转换

    #b、d、o、x分别是二进制、十进制、八进制、十六进制

    方式一:{:条件}.format(参数)

    a = 3.14159
    b = '{:.2f}'.format(a)
    print(b)
    #输出:3.14
    
    c = '{:+.2f}'.format(a)
    print(c)
    #输出:+3.14

    方式二:format(参数, '.条件'),不需要{: }

    # '+.2f':此处只能是具体数字2,不能是字符变量;

    b = format(3.14159, '+.2f')
    print(b)
    #输出:+3.14
    参数 条件的格式 输出 描述
    3.1415926 {:.2f} 3.14 保留小数点后两位
    3.1415926 {:+.2f} 3.14 带符号保留小数点后两位
    -1 {:+.2f} -1 带符号保留小数点后两位
    2.71828 {:.0f} 3 不带小数
    1000000 {:,} 1,000,000 以逗号分隔的数字格式
    0.25 {:.2%} 25.00% 百分比格式
    1000000000 {:.2e} 1.00E+09 指数记法
    25 {0:b} 11001 转换成二进制
    25 {0:d} 25 转换成十进制
    25 {0:o} 31 转换成八进制
    25 {0:x} 19 转换成十六进制

    三)字符串对齐于填充

    方式一:{:条件}.format(参数)

    方式二:format(参数, '.条件'),不需要{: }

    # format(参数, '.条件')中,'0>5'中,只能是5,不能是字符变量;

    参数 j条件格式 输出 描述
    5 {:0>2} 05 数字补零 (填充左边, 宽度为2)
    5 {:x<4} 5xxx 数字补x (填充右边, 宽度为4)
    10 {:x^4} x10x 数字补x (填充右边, 宽度为4)
    13 {:10}         13 右对齐 (默认, 宽度为10)
    13 {:<10} 13 左对齐 (宽度为10)
    13 {:^10}     13 中间对齐 (宽度为10)

    四)其它

    A、转义{和}符号

    跟%中%%转义%一样,formate中用两个大括号来转义

    B、format作为函数

    C、格式化datetime

    D、{}内嵌{}

    E、叹号的用法

    # !后面可以加s r a 分别对应str() repr() ascii()

    # 作用:在填充前先用对应的函数来处理参数

    差别就是repr带有引号,str()是面向用户的,目的是可读性,repr()是面向python解析器的,返回值表示在python内部的含义

    ascii()一直报错,可能这个是3.0才有的函数

  • 相关阅读:
    第五周学习总结
    第四周学习总结
    实验三报告
    第2,3周学习总结
    第二次实验报告
    实验一报告
    MyFirstStruts2
    java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
    Tomcat version 6.0 only supports J2EE 1.2, 1.3, 1.4,and Java EE 5 Web modules
    The JRE could not be found.Edit the server and change the JRE location.
  • 原文地址:https://www.cnblogs.com/volcao/p/8779618.html
Copyright © 2011-2022 走看看