'How to align/ format output in python
Hey I am building a class and in one of the methods the instruction is:
A long representation of the reviews for the movie, called longReview. This method takes no parameters. This method should return (as a string) a more detailed review of the movie.
Reference picture of correct format
Note that the colons must line up, and there is no space between the 5 stars and the colon in the third line of the review. You do not need to worry about aligning the numbers after the column – put a single space after the colon, and then the number of reviews of that type. The average review is rounded to one decimal place.
How would I build this so that my return output looks the same as that picture I know I would include elements like
def longReview(self):
# #this is what I want it to look like
# Dune (2021)
# Average Review: 4.7/5
# *****: 2
# **** : 1
# *** : 0
# ** : 0
# * : 0
return "{} {}".format(self.title,self.year) /n "Average Review: {}/5".format(self.review)
but I am unsure how to do the star thing and make sure everything is properly aligned
Solution 1:[1]
The best way to do it is to use string formating :
>>> print('{:<5}: {}'.format('*****', 2))
*****: 2
>>> print('{:<5}: {}'.format('****', 1))
**** : 1
>>> print('{:<5}: {}'.format('***', 0))
*** : 0
>>> print('{:<5}: {}'.format('*', 0))
* : 0
in the formating {:<5} the 5 means you want it to always take 5 caracters and the < means you want to align it to the left.
Complete doc here : https://docs.python.org/3/library/string.html#format-specification-mini-language
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Black Raven |
