curly braces in python

How to Print Curly Braces in String in Python

Python is a popular language that allows you to easily work with strings and text data. Sometimes you may need to print curly braces in string in Python. But if you are using format() function, then if you directly add curly braces in your string variables they will not be displayed. This is because curly braces have special meaning in python’s format function and they stand for variable substitution. In this article, we will learn how to do this.


How to Print Curly Braces in String in Python

Let us say you have the following string

>>> a="{dgfgfg}"


Let us say you call format() function on this string, which contains curly braces.

>>> a.format(42)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    a.format(42)
KeyError: 'dgfgfg'

As you can see, if your string variable contains curly braces, when you call format() function on it, you get the above error.

So you need escape the curly braces by using double curly braces as shown below.

>>> a="{{dgfgfg}}"

>>> a.format(42)
'{dgfgfg}'

This happens because format strings contain replacement fields within curly braces. So anything contained within curly braces is meant to be replaced by format function. So you need to use double curly braces to escape curly braces and display them in output.

In this short article, we have learnt how to print curly braces within string variables while using format() function.

Also read:

How to Set Timeout on Python Function Call
How to Set Default Value for Datetime Column in MySQL
How to Empty Array in JavaScript
How to Set Query Timeout in MySQL
How to Count Frequency of Array Items in JavaScript

Leave a Reply

Your email address will not be published.