Brace characters are often useful in strings, aside from formatting. We need a way to escape them in situations where we want them to be displayed as themselves, rather than being replaced. This can be done by doubling the braces. For example, we can use Python to format a basic Java program:
classname = "MyClass"
python_code = "print('hello world')"
template = f"""
public class {classname} {{
public static void main(String[] args) {{
System.out.println("{python_code}");
}}
}}"""
print(template)
Where we see the {{ or }} sequence in the template—that is, the braces enclosing the Java class and method definition—we know the f-string will replace them with single braces, rather than some argument in the surrounding methods. Here's the output:
public class MyClass { public static void main(String[] args) { System.out.println("print('hello world')"); } }
The class name and contents of the output have been replaced with two parameters, while the double braces have been replaced with single braces, giving us a valid Java file. Turns out, this is about the simplest possible Python program to print the simplest possible Java program that can print the simplest possible Python program.