Please note this is from a learning exercise for myself to learn OOP. Please do not tell me to use numpy because the point of this exercise for me is to learn about creating classes and defining methods (however, if numpy or any other library contains a method that does exactly what I'm asking for then feel free to point me to it so I can see what the code looks like).
I'm using Python2.7 and I would like to return a string that gives me a spaced out matrix with square brackets on each end, like this:
[ 12 -42 ]
[ 3 4 ]
I want to return it as a string (rather than print it in place) because I'm overloading the str method. I've seen similar questions which helped me get to the point where I am now. But I'm still not sure if what I want to do is entirely possible the way I want to do it.
This was my first attempt using nested for loops:
def __str__(self):
""" Return each entry in the Matrix spaced apart."""
string_out = ""
for row in self.matrix:
string_out += "["
for num in row:
string_out += "%4d"%num
string_out += "]\n"
return string_out
where self.matrix
is my array that stores the values of the Matrix object I'm working with. In my example instance self.matrix = [[12,-42],[3,4]]
).
The for loops give me what I want, however I wanted to see if I could do this in a list comprehension way.
This is my attempt so far with list comprehension:
def __str__(self):
return "]\n".join("".join( "{:4}".format(num) for num in row) for row in self.matrix) +"]"
This gives me:
12 -42]
3 4]
which is nearly there, but I can't figure out if there's a way to get the square brackets in the front without having them also repeat in between the numbers.
Would someone be able to either help me out, or put me out of my misery by confirming that it's not possible?
Seems to me that you're pretty close. You only need to alter what you're join
ing on, and add an additional left bracket at the beginning. How about:
return "[" + "]\n[".join("".join( "{:4}".format(num) for num in row) for row in self.matrix) +"]"
Which results in:
[ 12 -42]
[ 3 4]