Home > front end >  What are allowed as literal characters in f-strings?
What are allowed as literal characters in f-strings?

Time:12-20

In the BNF rules for the formatted string literals (f-strings):

f_string ::= (literal_char | "{{" | "}}" | replacement_field)*
...
literal_char ::= <any code point except "{", "}" or NULL>

What does it mean specifically regarding the NULL?

It looks like f'\0' is valid.

CodePudding user response:

The allowed code points are any code point except "{", "}" or NULL.

The string f"\0" contains two code points \ and 0. They form an escape sequence that represents a null byte – just like \n represents a newline. This is similar to how the source code (a string) True represents the boolean true value (an object).
Notably, these representations are not the thing they represent. Placing \0 in an f-string is fine because it is not a NULL itself.

>>> # the source code representing a number is not the number
>>> source = "1337"
>>> eval(source) == source
False

Note that CPython and PyPy do not accept NULL bytes in source code to begin with.

  • Related