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'
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.
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 ( %% ).
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.
Python f-string escaping characters To escape a curly bracket, we double the character. A single quote is escaped with a backslash character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With