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 trialLuke Maschoff
820 PointsIn Python, what is the purpose of .format()?
Confused on what .format() does in Python.
2 Answers
Steven Parker
231,275 PointsThe "format" method looks through the string it is applied to for placeholder tokens (usually "{}"), and replaces each of them with one of the arguments passed to it. It's a good way to add data from variables into messages.
For more details, see the Custom String Formatting section of the Python reference manual.
Øyvind Andreassen
16,840 PointsBoth solution will work, I haven't heard that keyword arguments are deprecated as they give very clear instructions on what should go where. Tested in Python 3.7.0.
With the f-strings in Python you can also do:
def favorite_food(name, food):
return f"Hi, I'm {name} and I love to eat {food}!"
This article goes through pros and cons with all approaches.
Steven Parker
231,275 PointsTake a look at the manual page I linked in the answer. It contains this:
Changed in version 3.7: A format string argument is now positional-only.
Am I misunderstanding that?
Mark Nembhard
1,387 PointsHi . the chat about the deprecated format is interesting. If you have quite a few place holders then having the names of the string variables that you want to place in them makes sense and less error prone. So instead of the .format(x,y,z) variables that have to go in sequential order you can just list the variable names and they will jump into the place-holders where they are mentioned. Please correct me if i am wrong as i am new to this
Steven Parker
231,275 PointsThe keyword arguments can be handy, and they do still work for now, but the manual says they are no longer "official". As to why they are moving away from them, I have no idea!
Øyvind Andreassen
16,840 PointsØyvind Andreassen
16,840 PointsTo elaborate on Steven's answer.
If you want to have a string formatted a certain way each time you could do something like this:
So each time you call
favorite_food
you can pass in a name and a food and get the string you expect.Steven Parker
231,275 PointsSteven Parker
231,275 PointsIf I understand what I just read in the manual link given above, keyword argments are now deprecated for "format". So refactoring that example for the current version might look like this: