How to print literal curly-brace characters in a String and also use .format it with Python?

Estimated read time 2 min read

To print literal curly-brace characters in a string and also use the .format() method in Python, you can use double curly braces {{ and }} to represent a literal curly brace.

Here’s an example:

name = "Alice"
age = 28

# Using literal curly braces and .format() method
message = "The name is {{}} and the age is {{}}.".format(name, age)
print(message)

In the example above, the string message contains double curly braces {{ and }} to represent literal curly braces. When you use .format() on the string, the curly braces within the string are not treated as placeholders for variable substitution. Instead, they are printed as literal curly braces.

If you want to substitute variables into the string, you can use the format placeholders {} as usual:

name = "Alice"
age = 28

# Using literal curly braces and .format() method with variable substitution
message = "The name is {{}} and the age is {{}}.".format(name, age)
formatted_message = message.format(name, age)
print(formatted_message)

In this case, the formatted_message variable is created by calling the .format() method on the message string and providing the values for name and age as arguments.

By using double curly braces {{}} for literal curly braces and using the .format() method, you can include curly braces within a string without triggering variable substitution.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply