同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
Dictionary-Based String Formatting Expressions
String formatting also allows conversion targets on the left to refer to the keys in a dictionary on the right and fetch the corresponding values. I haven’t told you much about dictionaries yet, so here’s an example that demonstrates the basics:
>>> "%(n)d %(x)s" % {"n":1, "x":"spam"}
'1 spam'
Here, the (n) and (x) in the format string refer to keys in the dictionary literal on the right and fetch their associated values. Programs that generate text such as HTML or XML often use this technique—you can build up a dictionary of values and substitute them all at once with a single formatting expression that uses key-based references:
>>> reply = """ # Template with substitution targets
Greetings...
Hello %(name)s!
Your age squared is %(age)s
"""
>>> values = {'name': 'Bob', 'age': 40} # Build up values to substitute
>>> print(reply % values) # Perform substitutions
Greetings...
Hello Bob!
Your age squared is 40
This trick is also used in conjunction with the vars built-in function, which returns a dictionary containing all the variables that exist in the place it is called:
>>> food = 'spam'
>>> age = 40
>>> vars()
{'food': 'spam', 'age': 40, ...many more... }
When used on the right of a format operation, this allows the format string to refer to variables by name (i.e., by dictionary key):
>>> "%(age)d %(food)s" % vars()
'40 spam'
We’ll study dictionaries in more depth in Chapter 8. See also Chapter 5 for examples that convert to hexadecimal and octal number strings with the %x and %o formatting target codes.
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏