Search code examples
pythonf-stringone-liner

f-string with curly brace and function


I searched for existing answers. I found answers for printing curly braces, but they do not include executing a function inside the f-string as well. The one marked as duplicate did not solve my problem.

Part of the string that I'm trying to print is resolved from a function. The static part of my string includes curly braces. I can perform the function using the old style, but I was hoping to do so with the new f-string. The final string should look like this:

test{aloha}

Old style works:

>>> print('test{%s}'%(aloha()))
'test{aloha}'

f-string - as expected, the curly braces are not printed:

>>> print(f"test{(aloha())}")
'testaloha'

f-string with double curly - function is not executed:

>>> print(f"test{{(aloha())}}")
"test{(xor('label'.encode(), 13).decode())}"

f-string escaping curly braces - syntax error:

>>> print(f"test\{{(aloha())}\}")
"SyntaxError: f-string: single '}' is not allowed"

f-string only escaping opening curly brace - no execution:

>>> print(f"test\{{(aloha())}}")
"test\{(xor('label'.encode(), 13).decode())}"

Am I just reaching too far?

Edit: shortened the original executed function to "aloha()", but people already responded with working answers while I was editing. Their answers are correct.


Solution

  • You need a triple curly. Each double curly makes for a single escaped curly braces:

    >>> f"{{{1}}}"
    '{1}'