0

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)
3
  • 2
    I don't know why OP would want this repr. Anyway, tuple will still have commas. Commented Sep 19, 2017 at 17:04
  • 3
    Actually, print '(%s)' % ' '.join(map(str, a)) or print('({})'.format(str(a)[1:-1]))? Commented Sep 19, 2017 at 17:06
  • Automated checker for school expects this output. ¯_(ツ)_/¯ Commented Sep 19, 2017 at 17:07

2 Answers 2

2

An option, as noted in the comments above (@Psidom) is to

  • convert the numpy output to a string using 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.