Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Python Data Types Strings

Sam Dale
Sam Dale
6,136 Points

Using str.format with a string that contains {}.

Hi there. I was just wondering what you need to do in order to use str.format with a string that contains {}. For example if you had the code:

print("Check {} {}".format("Here"))

Ideally I would want it to print: Check {} Here</br>

It throws an IndexError since format doesn't have enough chunks to insert into the instances of {}. But what if for some odd reason you needed to write {} in your string? Is there an escape character for { and }? I tried backslash, but that didn't work. Thanks for the help!

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The .format() method uses a special escape for braces: double-braces:

>>> "Check {{}} {}".format("Here")
'Check {} Here'

See Format String Syntax for more info

Sam Dale
Sam Dale
6,136 Points

Ah, very interesting. Thanks!

Whew! That's a lot of braces, and so what other escape characters are there in Python besides curly braces and backslash? Could we have used backslash in this example? In other words, are there times that you want to use one escape type vs. another?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Most of the time backslash is the escape character. format() is different because it may be operating on a string that has escaping for other purposes such as regex where a brace { is the start of a range value, and \{ is a regular character, so format needed something different.

If you had a regex that you wanted to construct using format the escaping can look crazy.

Say I wanted a regex that matched a specific number of characters between regular braces, I could use r'\{\w{4,}\}' to mean four or more word characters. But if I wanted to use a variable instead of 4, I could use format to fill it in.

First escape the existing braces

r'\{{\w{{4,}}\}}'

then insert the format field in place of the "4"

r'\{{\w{{{},}}\}}'

Then add the format method

r'\{{\w{{{},}}\}}'.format(count) Such as

$ python
Python 3.3.0 (default, Nov 26 2015, 16:04:52) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on unknown
Type "help", "copyright", "credits" or "license" for more information.
>>> count = 4
>>> reg = r'\{{\w{{{},}}\}}'.format(count)
>>> import re
>>> re.match(reg, "{abcd}").group()
'{abcd}'