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
Rodrigo Alarcon
8,028 Pointspython .format() explanation needed.
i have reviewed the video multiple times, but i am still finding the .format() confusing. please help me understand. an example would help
2 Answers
Modou Sawo
13,141 Points.format() can be used in a number of ways.
Let's say, you're writing a func in a letter guessing game, where you want it to print out each wrong strike:
Here for ex:
good_choice = [] #good_choice is a list
bad_choice = [] # And so is bad_choice
def draw(bad_choice, good_choice, secret_word): # The func. draw holds these arguments inside the bracket
print("Strikes: {}/7.".format(len(bad_choice))) # Here I "formatted" {} by the len (length) of bad_choice
So for each bad_choice the player enters, a line will print out, i.e. :
The first strike : "Strikes: 1/7"
2nd strike : "Strikes: 2/7"
And so on. So here, I used .format() to print out each strike made
Hope this helps.
Steven Parker
243,656 PointsThink of .format as the "fill in the blank" function.
Where the string it is used on has a "blank" (a placeholder identified by braces), the .format function will replace that "blank" with a passed argument. Examples:
name = "Joe"
food = "cheese"
print("The customer's name is {}".format(name)); # will print "The customer's name is Joe."
print("{} likes to eat {}.".format(name, food)) # will print "Joe likes to eat cheese."