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 Basics (2015) Python Data Types Splitting and Joining

.format()

He pulled the .format() function out of no where and I just lost it after that. also what is the {} for when he does that line of code towards the end using the .format() function?

1 Answer

Steven Parker
Steven Parker
221,309 Points

The {} symbols are the "placeholder".

Those symbols indicate the place in the template string where the format function will put the argument it is given. For example:

name = "Python"
guess = "{} is fun to use.".format(name)
print(guess)  # this will show: "Python is fun to use."

Can you explain what happened in this line of code from the video? "My favorite flavors are: {}".format(", ".join(flavors))

Steven Parker
Steven Parker
221,309 Points

Ok, I'll break it down into steps:

  • at the start, flavors is a list of 3 strings: ['chocolate', 'mint', 'strawberry']
  • ", ".join(flavors) :point_left: this converts the list into one string: 'chocolate, mint, strawberry'
  • "My favorite flavors are: {}".format(:arrow_up:) :point_left: this puts the new string in place of the {}
  • 'My favorite flavors are: chocolate, mint, strawberry' :point_left: so this is the final result