Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
edited by

I have a string. If I need curly braces, it further exploits the f-strings feature. Is there a language punctuation/syntax which can help me here in this case?

Here are two different ways it doesn't work. I might want to incorporate the literal text  "{bar}" as a component of the string.

foo = "test"

fstring = f"{foo} {bar}"

NameError: name 'bar' is not defined

fstring = f"{foo} \{bar\}"

SyntaxError: f-string expression part cannot include a backslash

Desired output:

'test {bar}'

1 Answer

0 votes
by (26.4k points)
edited by

In spite of the fact that there is a custom syntax error from the parser, a similar trick fills in with respect to calling .format on normal strings.

Use double curlies:

>>> foo = 'test'

>>> f'{foo} {{bar}}'

'test {bar}'

It's referenced in the spec here and the docs here.

Are you looking for a good python tutorial? Come and Join the python course fast!

Watch this video tutorial on how to become a professional in python

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 19, 2020 in Python by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...