Carly's Clippers (step 4) - .format?

Hi everyone,

I am having trouble understanding the solution in the video solution for printing the result in step 4.

The dev in the video uses something I am not familiar with (unless I already forgot): ${}.format. I am afraid I don’t understand this bit.

What I tried is the below, but the new line is not working.

average_price = ["Average Haircut Price: \n" + str(total_price/len(prices))]

Any chance if someone could explain what is the ${}? Also, is my code wrong?

Many thanks!!

Video solution:

That is a placeholder for interpolating expressions within a string. The variables will be passed into the .format() method.

Since we can’t see the code where you are using ${}, we are left to assume. If your code looks something like this:

someValue = 10.53
print("Some random string with an amount we want to display as dollars to follow ${}".format(someValue))

The $ is just a character to be printed. The {} is a placeholder that will be replaced with the value of the argument passed to the .format() method. In this case the output is:

Some random string with an amount we want to display as dollars to follow $10.53

If you could post your entire code, we will be able to expound more if necessary.

Also, regarding your average_price assignment, is average_price supposed to be a list?

Hello! Thank you. That makes sense, although I have not yet met with the .format in this course.

Regarding average_price, no, it’s a variable.

The full code of the dev in the video is (some code comes before, defining three lists, one of them being prices):

Total_price = 0
For price in prices:
  total_price += price
average_price = total_price / len(prices)
Print(“Average Price:

UPDATE: As for my code, I’ve removed the brackets and now it prints the right answer.

1 Like

I quite like the following link for a quick intro to string formatting-

If you were curious about the numbering in the replacement specifier it’s fairly straightforward and relates to the arguments you pass on to .format().

"{1} is the second argument. {0} is the first".format('yellow', 3)
# Out: '3 is the second argument. yellow is the first'

I think the question about the list was asked since you wrapped your string concatenation with the square paranthese [ ] which would make a list (even if it’s only one item long).

1 Like