zoukankan      html  css  js  c++  java
  • 字符串格式化

    字符串格式化

    一、百分号

    常用格式:

     1 tpl = "i am %s" % "alex"
     2  
     3 tpl = "i am %s age %d" % ("alex", 18)
     4  
     5 tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}
     6  
     7 tpl = "percent %.2f" % 99.97623
     8  
     9 tpl = "i am %(pp).2f" % {"pp": 123.425556, }
    10  
    11 tpl = "i am %.2f %%" % {"pp": 123.425556, }

    %s #可取任何值

    %d #可取整数值

    %f #打印浮点数,比如%.2f 表示取两位小数

    %. #截取长度,比如%.4s 表示截取4位字符串

    %% #百分比符号

    %(pp) #取字典中的K值

    PS:

    print('root','x','0','qq',sep=':') #可输出

    二、format格式化

    常用格式:

    tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
      
    tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
      
    tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
      
    tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
      
    tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
      
    tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
      
    tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
      
    tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
      
    tpl = "i am {:s}, age {:d}".format(*["seven", 18])
      
    tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
      
    tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
     
    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
     
    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
     
    tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
     
    tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

    {0} #取参数中第0位的值

    * #取列表中的值所需要的前置符号

    ** #取字典中的值所需要的前置符号

    :s #可取任何值

    :f #打印浮点数,比如%.2f 表示取两位小数

    :b #二进制

    :o #八进制

    :d #整型/十进制

    :x #十六进制/小写

    :X #十六进制/大写

    :% #百分比,默认后6位

  • 相关阅读:
    【字符串哈希】The 16th UESTC Programming Contest Preliminary F
    【推导】The 16th UESTC Programming Contest Preliminary L
    【推导】zoj3846 GCD Reduce
    【spfa】【动态规划】zoj3847 Collect Chars
    【搜索】【组合数学】zoj3841 Card
    【贪心】【字典树】Gym
    【贪心】【后缀自动机】Gym
    【拉格朗日插值法】【找规律】【高精度】Gym
    【二分】【动态规划】Gym
    【软件开发综合实验】文本压缩软件
  • 原文地址:https://www.cnblogs.com/lishuangtu/p/8919016.html
Copyright © 2011-2022 走看看