If you want to outsource the formatting to have a clean usage like this or similar
for data in your_seq:
print(data)
then you can consider using a class and design the output there. The advantage is a separation of formatting the data and the data itself. Here is one example with equal distributed length for each column using dataclass:
from dataclasses import dataclass
@dataclass
class Data:
ID: int
Amount: int
Rate: float
@property
def column_length(self):
return self.get_longest_column_length()
@classmethod
def get_longest_column_length(cls):
return len(max(cls.__annotations__, key=len)) + 1
@classmethod
def print_headline(cls):
length = cls.get_longest_column_length()
for var in cls.__annotations__:
print(f"{var:<{length}}", sep="", end="")
print()
def __repr__(self):
return (
f"{self.ID:<{self.column_length}}"
f"$ {self.Amount:<{self.column_length - 2}}"
f"{self.Rate:<{self.column_length}}"
)
For the usage, you can directly create Data instances or transform the items of an existing list to Data instances like this:
a = [[1, 10, 0.1], [2, 10, 0.2], [3, 11, 0.25]]
data = (Data(*el) for el in a)
Then you can do what I mentioned for the first code snippet:
Data.print_headline()
for date in data:
print(date)
There is maybe space for optimization here and there. And the low-level detail how to probably format your code is only moved away to the __repr__
method. So regarding this, there is not really something new in comparison to other answers. But you also mentioned
appropriate formatting, with column names, dollar signs, clean
spacing, nicely lined up, etc.
, so I had the feeling that using a class could be helpful as a potential starting point for more sophisticated formatting problems and trying to go a bit into the direction of separation of concerns (formatting vs. data).
The output for your provided data is:
ID Amount Rate
1 $ 10 0.1
2 $ 10 0.2
3 $ 11 0.25