Given a numpy array, a, how can i print it so the values are surrounded by parentheses instead of brackets?
import numpy as np
a = np.array([1,2,3])
>>> print(a)
[1 2 3]
I would like
>>> print(whatever)
(1 2 3)
An option, as noted in the comments above (@Psidom) is to
str(). then manually replace the opening bracket and closing bracket with parenthesis using replace(). replace() is a string method
import numpy as np
a = np.array([1,2,3])
print(a)
[1 2 3]
print(str(a).replace('[', '(').replace(']', ')'))
(1 2 3)
In this case, str() converts the output from numpy to the string representation so that you can take advantage of the various string methods associated with strings.
With the output converted to a string, you can then immediately call the replace() method... since the output of the replace() method is also a string, you can chain replace() methods sequentially to do multiple replacements.
Alternatives to using chained replace() methods would be to create a regular expression and use something like re.sub(), but that seems like overkill for a simple case like this.
numpy uses [] just as list does. Structured array records are marked with () to highlight their difference:
In [286]: a = np.array([1,2,3])
In [287]: a.view('i,i,i')
Out[287]:
array([(1, 2, 3)],
dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])
Extracting a record gives a tuple like display:
In [288]: a.view('i,i,i')[0]
Out[288]: (1, 2, 3)
In [289]: tuple(a.tolist())
Out[289]: (1, 2, 3)
There's isn't a normal display that uses () and omits the commas. To get that you need to do your own formatting, or perform some sort of replace on the common display.
If the checker expects () and no comma, there's something wrong. That's not normal.
print '(%s)' % ' '.join(map(str, a))orprint('({})'.format(str(a)[1:-1]))?