1 格式化输出 - 与C语言类似的 % 方式
%d %s %f %x
a = 0b10111011
b = 0xc5f
print('Binary is %d, hex is %d' % (a, b))
# 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
- 解决方案:用字典代替元组
```python
key = 'my_var'
value = 1.234
old_way = '%-10s = %.2f' % (key, value)
new_way = '%(key)-10s = %(value).2f' % { 'key': key, 'value': value} # Original
reordered = '%(key)-10s = %(value).2f' % { 'value': value, 'key': key} # Swapped
assert old_way == new_way == reordered
2 不易阅读
- 作出小的修改时,不方便阅读与对应
3 重复性太高
如果你在一个表达式中想打印多次同一个值,会出现多次重复
template = '%s loves food. See %s cook.'
name = 'Max'
formatted = template % (name, name)
print(formatted)
>>> 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
<a name="RMVR6"></a>
### 4 使用字典会增加冗长的语言
```python
soup = 'lentil'
formatted = 'Today\'s soup is %(soup)s.' % {'soup':soup}
print(formatted)
>>>
Today's soup is lentil.
2 格式化输出 - 使用 format 或 str.format
- https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#formatted-string-literals
仍存在一些问题,如冗余。
https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#formatted-string-literals ```python key = “my_var” value = 1.234
formatted = f’{key!r:<10} = {value:.2f}’ print(formatted)
总结
- 采用 % 操作符把值填充到 C 风格的格式字符串时会遇到许多问题,而且这种写法比较繁琐。
- str.format 方法专门用一套迷你语言来定义它的格式说明符,这套语言给我们提供了一些有用的概念,但是在其他方面,这个方法还是存在与 C 风格的格式字符串一样的多种缺点,所以我们也应该避免使用它。
- f-string 采用新的写法,将值填充到字符串之中,解决了 C 风格的格式字符串所带来的最大问题。
- f-string 是个简洁而强大的机制,可以直接在格式说明符里嵌入任意 Python 表达式。