Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 455
user3683238 Avatar asked May 28 '14 10:05

user3683238


People also ask

How do you escape a string format in Python?

You can use the backslash (\) escape character to add single or double quotation marks in the python string format. The \n escape sequence is used to insert a new line without hitting the enter or return key. The part of the string after \n escape sequence appears in the next line.

How do you escape a string format?

String's format() method uses percent sign( % ) as prefix of format specifier. For example: To use number in String's format() method, we use %d , but what if you actually want to use percent sign in the String. If you want to escape percent sign in String's format method, you can use % twice ( %% ).

What does %% mean in Python?

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.

How do you escape brackets in F string Python?

Python f-string escaping characters To escape a curly bracket, we double the character. A single quote is escaped with a backslash character.


1 Answers

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.

like image 132
Martijn Pieters Avatar answered Nov 08 '22 16:11

Martijn Pieters