zoukankan      html  css  js  c++  java
  • 【Python】字符串格式化调用方法

    一、基础知识

    • str.format()的使用语法
      在主体字符串(string)中,花括号通过位置(例如,{1})或关键字(例如,{food})指出替换目标及将要插入的参数。
      该方法创建并返回一个新的字符串对象,可以被立即打印或保存起来。
      例如:
    template = '{0}, {1} and {2}'
    template.format('spam', 'ham', 'eggs')
    # spam, ham and eggs
    
    template = '{motto}, {pork} and {food}'
    template.format(motto = 'spam', pork = 'ham', food = 'eggs')
    # spam, ham and eggs
    
    template = '{motto}, {0} and {food}'
    template.format('ham', motto = 'ham', food = 'eggs')
    
    • 主体字符串也可以是一个临时字符串常量,并且任意的对象类型都可以替换。
    '{motto}, {0} and {food}'.format(42, motto=3.14, food = [1,2])
    # '3.14, 42 and [1,2]'
    

    二、添加键,属性和偏移量

    • 格式化字符串可以指定对象属性和字典键:方括号指定字典键,点表示位置或关键字所引用的一项的对象属性
    >>> import sys
    >>> '{1[spam]} and {0.platform}'.format(sys, {'spam':'laptop'})
          out: laptop and win32
    
    >>> '{config[spam]} and {sys.platform}'.format(sys = sys, config = {'spam':'laptop'})
          out: laptop and win32
    
    • 格式化字符串中的方括号可以指定列表(及其他序列)的(正)偏移量以执行索引
    >>> somelist = list('SPAM') # ['S', 'P', 'A', 'M']
    >>> 'first = {0[0]} and second = {0[1]}'.format(somelist)
         out: first = S and second = P
    

    三、添加具体格式化

    • str.format()的替代目标语法
      形式化结构:{fieldname!conversionflag:formatspec}
    1. fielname 是指定参数的一个数字或关键字,后面跟着可选的“.name”或“[index]”成分引用
    2. conversionflag 可以是r, s, 或者a分别是在该值上对rper, str 或ascii内置函数的一次调用
    3. formatspec 指定了如何表示该值,包括字段宽度,对齐方式,补零,小数点精度等细节,并且以一个可选的数据类型编码结束。

    formatspec 组成形式如下:
    [[fill]align][sign][#][0][width][.precision][typecode]

    • align 可能是>, <,= 或 ^ , 分别表示左对齐,右对齐,一个标记字符后的补充或居中对齐
    • formatspec 也包含嵌套的,只带有{}的格式化字符串,它从参数列表动态地获取值
    • 一些常见示例如下:
    >>> '{0:10} = {1:10}'.format('spam', 123.456) # 第一个位置参数,10个字符宽
          out: 'spam      =      123.456'
    >>> '{0:>10} = {1:<10}'.format('spam', 123.456) # 第一个位置参数右对齐,10个字符宽;第二个位置参数左对齐,10个字符宽
          out:'     spam = 123.456    '
    >>> '{0.platform:>10} = {1[item]:<10}'.format(sys, dict(item='laptop'))
          out:'     win32 = laptop     '
    
    • 浮点数代码示例如下:
    >>> '{0:e}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159)
          out: 3.141590e+00, 3.142e+00, 3.14159
    >>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)
          out: 3.141590, 3.14, 003.14
          # {2:g} 表示第三个参数默认根据“g”浮点数表示格式化
          # {1:.2f}指定了带有2个小数位的“f”浮点数格式
          # {2:06.2f}添加一个6字符宽的字段并且在左边补充0
    
    • 嵌套式格式化语法,从参数列表动态地获取
    >>> '{0:.{1}f}'.format(1/3.0, 4)
          out: 0.3333
    
  • 相关阅读:
    2018年9月28日CCPC秦皇岛站参赛总结
    数学:二次剩余与n次剩余
    数学:拓展Lucas定理
    BZOJ2301:莫比乌斯反演+二维容斥解决GCD范围计数
    数学:莫比乌斯反演-约数个数和
    数学:莫比乌斯反演-GCD计数
    关于cnblogs至github上blog的搬迁
    友链——一群dalao
    折半搜索(meet in the middle)
    关于爆搜
  • 原文地址:https://www.cnblogs.com/xiaofeiIDO/p/12050089.html
Copyright © 2011-2022 走看看