Depending on how much extra code/complexity you want for a solution here, you can do a few things. You can use a custom function in the print
statement if you really want fine-grained control over the output (using code offered up in some of the other proposed solutions), but a less cumbersome approach that still gives you a decent amount of flexibility is to use the array2string function already included in Numpy.
A few examples using your scenario:
>>> print(np.array2string(a=M))
[[1. 0. 0. ]
[0. 1.5 0. ]
[0. 0. 2. ]]
- Using the
separator
argument to add a bit of padding around elements:
>>> print(np.array2string(a=M, separator=' '))
[[1. 0. 0. ]
[0. 1.5 0. ]
[0. 0. 2. ]]
- If the leading and trailing brackets are bothersome, you can go a bit further with the
print
statement (array2string
doesn't give you a way to change this) itself, doing a bit of manipulation to account for the character spacing with the brackets being removed:
>>> print(' ' + np.array2string(a=M, separator=' ')[1:-1])
[1. 0. 0. ]
[0. 1.5 0. ]
[0. 0. 2. ]
Note that the last scenario still leaves a space at the beginning of each line. You could use regexes to clean this up.
I realize that this may not be exactly what you are looking for in terms of output, but I thought I might offer up a lighter weight alternative that gets you mostly there.