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 trialamandae
15,727 PointsPrinting 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
Treehouse Moderator 68,454 PointsHey 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!!
amandae
15,727 PointsThank you so much! Your answer is wonderfully helpful!