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 Challenge Solution

Ash Skelton
Ash Skelton
3,745 Points

String formatting question...

In the solution video, string formatting is used like:

understanding = input("{}, do you understand Python while loops?\n(Enter yes/no)".format(name))

Before watching this, my solution was:

understanding = input(name + ", do you understand Python while loops?\n(Enter yes/no)")

This worked and my output was exactly the same. My question is whether there is a preferred method in the Python community or is there no reason why I couldn't use my solution in the real world?

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

Yes, your solution is just fine and will work perfectly. And in truth format() isn't strictly needed, but is super handy.

There is some definite value to using format method and "f" strings that were introduced in Python 3.6. While early on it might seem more complex, the format strings can save you work and can make for more precise formating.

Strings aren't the sole domain of printing but may be used in rendering tasks or querying-- in those cases, it is much more clear to use format() and f strings.

Reasons to use .format and "f" strings in projects:

  1. format strings support named and positional parameters. The named and positional parameters can be repeated.

  2. format strings are often used as "templates" for printing, rendering, or querying. You will see quite a lot of this in Intermediate Python.

  3. format strings can be used as multi-line strings. Super useful for things like "mail merge" or messaging.

Ash Skelton
Ash Skelton
3,745 Points

Thanks so much for the quick and detailed response, Jeff! It's much appreciated :)