5

I have this code

class = "maximum"
s = f"""The code for {class} is {3854-st56}"""
print(s)

I want this to output:

>> The code for maximum is {3854-st56}

But the f-string doesn't recognize the curly brackets around 3854-st56 and instead thinks I am trying to input actual Python code. How do I make the f-string recognise that the curly brackets are string literals.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Vidit Gautam
  • 97
  • 1
  • 5

2 Answers2

8

To escape curly braces, duplicate them:

>>> x="abc"
>>> f"{x} {{x}}"
'abc {x}'

You can also look at the PEP for more information: https://www.python.org/dev/peps/pep-0498/#escape-sequences

0xff
  • 81
  • 2
5

You need to use curly bracket twice if you are assigning variable value and once if you are putting on a value:

Class = "maximum"
s = f"""The code for {{{Class}}} is {{'3854-st56'}}"""
print(s)

The code for {maximum} is {3854-st56}
Pygirl
  • 12,969
  • 5
  • 30
  • 43
  • Use double braces {{ or }} so your code becomes: sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", prop.Type, prop.Name)); // For prop.Type of "Foo" and prop.Name of "Bar", the result would be: // public Foo Bar { get; private set; } – Pratham_Amitabh Jul 05 '21 at 09:58