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 Python Basics (Retired) Putting the "Fun" Back in "Function" Shopping List Redux

helmi al kindy
helmi al kindy
1,371 Points

Why did you use format function ?

At 1:20 in the video or line 10 on the script, .format(... was used. What does that do ?

helmi al kindy
helmi al kindy
1,371 Points

Ok thanks so it's like %s, %r, etc

jayj
jayj
2,515 Points

Correct, this is the new method of string manipulation in Python 3.

In Python 2 it would look similar to this.

print "My name is %s" % "Jay"

Glad to help. :)

1 Answer

jayj
jayj
2,515 Points

When the format() method is called at the end of a string, what it does is takes any arguments and replaces any replacement fields (Curly braces) in your string with your arguments.

So, for example let's use two different prints, the first we'll just pass strings, the second we will pass a string and add some numbers together.

print("Hello, my name is {} and I like to help with {} on TeamTreeHouse".format("Jay", "Pyt" + "hon"))
print("I have studied {} for {} hours this week!".format("Python", 5+5+6))

This example is going to return the follow text.

Hello, my name is Jay and I like to help with Python on TeamTreeHouse

I have studied Python for 16 hours this week!

Hope this helps!

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello jayj. I have change your comment into an answer.

;)

jayj
jayj
2,515 Points

Oh boy, I am terrible at this new type of forum software. :) Just fixed up my formatting as well. Thanks Vittorio!