1 格式化输出 - 与C语言类似的 % 方式

  • %d %s %f %x

    1. a = 0b10111011
    2. b = 0xc5f
    3. print('Binary is %d, hex is %d' % (a, b))
    4. # Binary is 187, hex is 3167

    存在问题

    1 可能出现对应错误

  • 如果你改变了格式化表达式右边的元组中的数据值的类型或者顺序,将会报错 ```python key = ‘my_var’ value = 1.234 formatted = ‘%-10s = %.2f’ % (key, value) print(formatted)

    my_var = 1.23

wrong

key = ‘my_var’ value = 1.234 formatted = ‘%-10s = %.2f’ % (value, key) print(formatted)

Traceback …

TypeError: must be real number, not str

  1. - 解决方案:用字典代替元组
  2. ```python
  3. key = 'my_var'
  4. value = 1.234
  5. old_way = '%-10s = %.2f' % (key, value)
  6. new_way = '%(key)-10s = %(value).2f' % { 'key': key, 'value': value} # Original
  7. reordered = '%(key)-10s = %(value).2f' % { 'value': value, 'key': key} # Swapped
  8. assert old_way == new_way == reordered

2 不易阅读

  • 作出小的修改时,不方便阅读与对应

image.pngimage.png

3 重复性太高

  • 如果你在一个表达式中想打印多次同一个值,会出现多次重复

    1. template = '%s loves food. See %s cook.'
    2. name = 'Max'
    3. formatted = template % (name, name)
    4. print(formatted)
    5. >>> Max loves food. See Max cook.
  • 解决方案:用字典代替元组 ```python name = ‘Max’

template = ‘%s loves food. See %s cook.’ before = template % (name, name) # Tuple

template = ‘%(name)s loves food. See %(name)s cook.’ after = template % {‘name’: name} # Dictionary

assert before == after

  1. <a name="RMVR6"></a>
  2. ### 4 使用字典会增加冗长的语言
  3. ```python
  4. soup = 'lentil'
  5. formatted = 'Today\'s soup is %(soup)s.' % {'soup':soup}
  6. print(formatted)
  7. >>>
  8. Today's soup is lentil.

2 格式化输出 - 使用 format 或 str.format

formatted = f’{key!r:<10} = {value:.2f}’ print(formatted)

> ‘my_var’ = 1.23 ```

总结

  • 采用 % 操作符把值填充到 C 风格的格式字符串时会遇到许多问题,而且这种写法比较繁琐
  • str.format 方法专门用一套迷你语言来定义它的格式说明符,这套语言给我们提供了一些有用的概念,但是在其他方面,这个方法还是存在与 C 风格的格式字符串一样的多种缺点,所以我们也应该避免使用它。
  • f-string 采用新的写法,将值填充到字符串之中,解决了 C 风格的格式字符串所带来的最大问题。
  • f-string 是个简洁而强大的机制,可以直接在格式说明符里嵌入任意 Python 表达式。