String formatting in the project "Carly's clippers"

Hello

I have a question about the project “Carly’s clippers”.
https://www.codecademy.com/courses/learn-python-3/projects/carlys-clippers

I tried doing the project on my own and then looking at the video guide. My way of writing worked fine and then the guide did something very different. And i am now wondering why he did it that way and what the advantage is and so on.

My code:

average_price = total_price / len(prices)
print("Average Haircut Prices: " +  str(average_price))

The guide:

average_price = total_price / len(prices)
print("Average Haircut Prices: ${0}".format(average_price))

I have never used .format() in the previous chapters of the course. Hope someone can clear things up for me. What is best practice and why?

I think this link- Python String Formatting Best Practices – Real Python covers most of the options for string formatting. In many cases you’ll have an easier time using the proper formatting tools instead of concatenation (especially when dealing with the formatting of things like numbers). So it’s somewhat up to you but f-strings and .format tend to be a little nicer.

https://pyformat.info/ has some helpful examples of padding and truncation etc. though it doesn’t cover f-strings but the formatting syntax is very similar anyway.

2 Likes

okay thanks!

I have noticed now when i moved into the chapters lists and loops that they introduce features and functions that has not been covered or explained. This was one and another example is .pop().
I have searched on google on this but sometimes its not easy to understand it fully.

Do you have any advice on how to think and where to go for general information?

If all else fails, consult the python documentation:

https://docs.python.org/3.9/tutorial/datastructures.html

2 Likes

Hunting down guidance is a skill in its own right at times :stuck_out_tongue:. The docs are always a good place to start- 3.9.1 Documentation and it’s worth learning your way around them (I think the layout of the Python docs is a bit odd and may take some time getting used to). A standard web search tends to give you pretty decent options too. You’ll start to notice helpful Q&A style things like various stack-exchange sites or for more detail and examples the blog-style posts can be helpful, or perhaps you prefer following a YT video.

If I can’t find info in the docs I tend to do a web search and filter out results by what I consider a “good” source but that’s a bit subjective. Without going into details of various pros and cons I’d tend towards stack-exchange and realpython as external sources for general python stuff but they’re far from the only options. You’ll inevitably shop around a bit and decide for yourself :slightly_smiling_face:.

2 Likes