Escape Curly Braces Using format() in Python

Escape Curly Braces Using format() in Python

  1. Use the format() Method in Python
  2. Print Curly Braces in a String Using the format() Method in Python

Escape in programming language means to print the characters in the form of literal text, which is unprintable in the code. In this article, we will learn about the format() method and how we can escape curly brace characters {} using the format() function.

Use the format() Method in Python

The format() is an in-built function in Python that is used to format a string and return a formatted output in our desired style.

Syntax:

"{}".format(value)
  1. The {} acts as a formatter/placeholder, and its value is replaced when the function is called.
  2. The value can be any string or character, etc., which is then replaced with the formatted in the output.

Example:

#Python 3.x
print("{} is a good option for python beginners".format("delftstack"))

Output:

delftstack is a good option for python beginners

Here, the value inside the format() function is replaced with curly braces and displayed in the output. We can also put 0 inside curly braces; it doesn’t make any difference.

Now, if you need your string value with curly braces in the output alongside using the format() function, all you need to do is put double curly braces with the placeholder. So, we have to put three curly braces instead of one.

Example 1:

#Python 3.x
print("{{{0}}} is a good option for python beginners".format("delftstack"))

Output:

{delftstack} is a good option for python beginners

Consider the following code for better understanding. This function accepts two arguments.

Example 2:

myname = 'jessica frank'
myage = 24
print("Name: {{{0}}} Age:{{{1}}}".format(myname, myage))

Output:

Name: {jessica frank} Age:{24}

So in these 2 example codes, we see that to print curly braces characters in the string, we have to use three pairs of curly brackets as a placeholder to get the required output.

Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python