user3683238
user3683238

Reputation: 83

How to escape dot in python str.format

I want to be able to access a key in a dictionary that has a dot with str.format(). How can I do that?

For example format for a key without a dot works:

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

But it doesn't when the key has a dot in it:

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

Upvotes: 8

Views: 3409

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121256

You cannot. The Format String Syntax supports only integers or valid Python identifiers as keys. From the documentation:

arg_name          ::=  [identifier | integer]

where identifier is defined as:

Identifiers (also referred to as names) are described by the following lexical definitions:

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

No dots (or semicolons) allowed.

You could use your dictionary as a second level object:

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

Here we assigned the dictionary to the name v, then index into it using a key name. These can be any string, not just identifiers.

Upvotes: 8

Related Questions