質問

A common technique for rendering values from template strings looks like this:

>>> num = 7
>>> template = 'there were {num} dwarves'
>>> print template.format(**locals())
there were 7 dwarves

This approach works for any data type that has a __str__ method, e.g. dicts:

>>> data = dict(name='Bob', age=43)
>>> template = 'goofy example 1 {data}'
>>> print template.format(**locals())
goofy example 1 {'age': 43, 'name': 'Bob'}

However it doesn't work when a dict item is referenced by key:

>>> template = 'goofy example 2 {data["name"]}'
>>> print template.format(**locals())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '"name"'

It's inconvenient, and seems odd, that an identifier that's valid in code outside the format string is invalid when used within the format string. Am I missing something? Is there a way to do this?

I'd like to be able to reference an element several layers down in a nested dictionary structure, like somedict['level1key']['level2key']['level3key']. So far my only workable approach has been to copy these values to a scalar variable just for string formatting, which is icky.

役に立ちましたか?

解決

You can do it by using {data[name]} instead of {data["name"]} in the string.

The types of things you can specify in a format string are restricted. Arbitrary expressions aren't allowed, and keys are interpreted in a simplified way, as described in the documentation:

it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string.

In this case, you can get your key out because it's a simple alphanumeric string, but, as the docs suggest, you can't always necessarily do it. If you have weird dict keys, you may have to change them to use them in a format string, or resort to other methods (like concatening string values explicitly with +).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top