Python Forum

Full Version: Printing array without commas
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I have got this output from my script:
Output:
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
I want to cover it to:
Output:
[[1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0]]
I tried:
a = np.asarray(a)
but output is:
Output:
array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
How resolve this?

I found that
a = np.asarray
worked correctly, but there was a problem with command print. When I used:
print ("a", a)
it gave me
Output:
('a', array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
But when I used:
print a
the output was:
Output:
[[1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0]]
If you try to print the array as an array, it will always contain comma's because that is how python represents the array contents.
You need to create a function that loops through the array and prints without commas.
Something like:
class PrintList:
    def print_list(self, aname):
        firstitem = True
        if isinstance(aname, list):
            print('[', end='')
            for item in aname:
                if isinstance(item, list):
                    if firstitem:
                        firstitem = False
                    else:
                        print()
                    self.print_list(item)
                else:
                    print(' {} '.format(item), end='')
            print(']', end = '')
        else:
            print('Not a list')

def tryit():
    p = PrintList()
    p.print_list([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])

if __name__ == '__main__':
    tryit()
test:
Output:
[[ 1.0 2.0 3.0 ] [ 4.0 5.0 6.0 ] [ 7.0 8.0 9.0 ]]