Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Sequences Sequence Iteration Iterating with Enumerate

Printing template literals in python "{item}" vs. "{}.format(item)"

Is there a reason why/helpful way to remember which format literal is used where? In most of the places I've learned so far, it works like this:

bugs = ["ants", "bees", "squash bugs", "chiggers"]
for e in bugs:
    print("There are so many {} outside!".format(e))

But, for f-string, it only works like this:

bugs = ["ants", "bees", "squash bugs", "chiggers"]
print("Bugs outside:")
for index, e in enumerate(bugs, 1):
    print(f'{index}. {e}')

I'm guessing there is a reason for this, but the switch from the .format method to putting the variables inside the curly braces isn't obvious to me. Thanks!

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,736 Points

Hey amandae, There are many ways to format a string in Python.

The f-strings, formatted string literals, is the latest addition, first appearing in Python 3.6.

The more complex (and flexible) previous method is using the str.format() method. This is is still widely used, and has additional features (like repeatable, reorderable fields) so expect it to stick around for a long time.

With the format method, the {} placeholders can taking on many forms:

  • as order-dependent placeholders when empty: "{} before {}".format(first, last)
  • as indexed-dependent placeholders when numbered: "{1} before {0}".format(goes2zero, goes2one)`
  • as named placeholders: "{first} before {last}".format(first=goes2first, last=goes2last)`

So, about remembering the difference. The "f" in front of f-strings can be thought of as fancy, where it is a shortcut to the named placeholder version of format without having to add the .format(first=first, last=last) method. The "f" can also be thought of as fast, since f-stings have been optimized to be the fasted string handling in python!!

Post back if you need more help. Good luck!!

Thank you so much! Your answer is wonderfully helpful!