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

Can you show me an example of why we would want to use the .format method over the ' + ' .join method?

In this video lesson we learned how to join strings and lists using two different methods.

flavors = ['chocolate', 'mint', 'strawberry']

', '.join(flavors)
'chocolate, mint, strawberry'
"my favorite flavors are: " + ', '.join(flavors)
'my favorite flavors are: chocolate, mint, strawberry'

"My favorite flavors are: {}".format(", ".join(flavors))
'My favorite flavors are: chocolate, mint, strawberry'

I am just looking for a deeper understanding of the two methods shown above. Why would I want to use one over the other. Can anyone give me a good example?

Thank you.

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Most of the time you want to avoid +. It's a convenience method for quickly joining some small strings. It used to be the only real way (other than % strings, which, let's not talk about those for now).

Using .format(), and the new f strings, gives you the ability to put multiple values into a string, otherwise formatted values into a string, or values that you want formatted when it goes into the string.

Some examples:

>>> names = ["Kenneth", "Alena", "Craig"]
>>> prices = [8, 2.5, 9.2232]
>>> "Some of our teachers are: {}".format(", ".join(names))
"Some of our teachers are: Kenneth, Alena, Craig"
>>> "It costs ${:.2f}".format(prices[-1])
"It costs $9.22"

There's a lot more you can do with string but this is a bit much to discuss in Python Basics, but maybe I'll do a "The Thing About Strings" workshop or something.

Thanks allot Kenneth. I really appreciate the quick response and your feed back. I've dabbled a bit with C# and Ruby, but I've found your classes on Python to be the easiest to learn for me.