How to avoid point in python str.format

I want to have access to a key in a dictionary that has a c str.format(). How can i do this?

For example, the format for a key without a dot works:

>>> "{hello}".format(**{ 'hello' : '2' })
'2'

But this is not so when the key has a point in it:

>>> "{hello.world}".format(**{ 'hello.world' : '2' })
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'hello'
+4
source share
2 answers

You can not. The string syntax format only supports integers or valid Python identifiers as keys. From the documentation:

arg_name          ::=  [identifier | integer]

where is identifier defined as :

Identifiers (also called names) are described by the following lexical definitions:

identifier ::=  (letter|"_") (letter | digit | "_")*

Dots (or semicolons) are not allowed.

:

"{v[hello.world]}".format(v={ 'hello.world' : '2' })

v, . , .

+6

string.Template - substitute

0

Source: https://habr.com/ru/post/1542308/


All Articles