2

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.

sirEgghead
  • 236
  • 1
  • 12
  • I know that one liners like what I'm trying to accomplish can reduce readability, but I'm trying to figure out how to do this for the sake of learning. Happy holidays! – sirEgghead Dec 25 '21 at 16:28
  • The question was closed and marked as a duplicate, but I do not think that it is a duplicate. I saw the question that was linked before I posted mine, but it did not help me since I have an additional part to my question that is relevant. I showed the results of the answer used from that linked question in my own question. :) – sirEgghead Dec 25 '21 at 19:13

2 Answers2

1

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

>>> f"{{{1}}}"
'{1}'
Bharel
  • 23,672
  • 5
  • 40
  • 80
0

This way:

f"test{{{(xor('label'.encode(), 13).decode())}}}"
Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26