53

I want to convert a = [1,2,3,4,5] into a_string = "1 2 3 4 5". The real numpy array is quite big (50000x200) so I assume using for loops is too slow.

5
  • :Check this stackoverflow.com/questions/5365520/… Commented Feb 20, 2012 at 11:13
  • 3
    Are you sure you really need a string representation for that big array? What for? Commented Feb 20, 2012 at 11:14
  • Afterwards I need to write this and three other arrays to a file. All the arrays have different sizes and I have to write them alternating into the file, so I am planing to do it manually using writeline. Commented Feb 20, 2012 at 11:21
  • 2
    The real question is why on earth doesn't np.array2string have an option to suppress the brackets. Commented Jun 11, 2019 at 0:07
  • Good question. Do you only want an answer for 1D arrays (per your example), 2D arrays (the most common), 3D or n-D arrays...? Commented Mar 15, 2020 at 4:02

7 Answers 7

70

You can use the join method from string:

>>> a = [1,2,3,4,5]
>>> ' '.join(map(str, a))
"1 2 3 4 5"
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, I tried join unsuccessfully before. Map is the missing piece for me.
a simpler variant (IMHO) would be with an iterator: ' '.join(str(n) for n in a)
Something like this looks good: def float2str(f): return '{:.5f}'.format(f) ' '.join(map(float2str, embeddings_fb.embed_token('.')))
@tito Is there any fast alternative to do the same thing. It is very slow for a big array.
@shaifaliGupta Printing is more bounded by I/O than CPU so I doubt alternative methods are going to be much faster.
29

np.savetxt

Python 3 (see also):

import numpy as np
import sys

a = np.array([0.0, 1.0, 2.0, 3.0])
np.savetxt(sys.stdout.buffer, a)

Python 2:

import numpy as np
import sys

a = np.array([0.0, 1.0, 2.0, 3.0])
np.savetxt(sys.stdout, a)

Output:

0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00

Control the precision

Use fmt:

np.savetxt(sys.stdout, a, fmt="%.3f")

output:

0.000
1.000
2.000
3.000 

or:

np.savetxt(sys.stdout, a, fmt="%i")

output:

0
1
2
3

Get a string instead of printing

Python 3:

import io
bio = io.BytesIO()
np.savetxt(bio, a)
mystr = bio.getvalue().decode('latin1')
print(mystr, end='')

We use latin1 because the docs tell us that it is the default encoding used.

Python 2:

import StringIO
sio = StringIO.StringIO()
np.savetxt(sio, a)
mystr = sio.getvalue()
print mystr

All in one line

Or if you really want all in one line:

a = np.array([0.0, 1.0, 2.0, 3.0])
np.savetxt(sys.stdout, a, newline=' ')
print()

Output:

0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00 

TODO: there is a trailing space. The only solution I see is to save to a string and strip.

Tested on Python 2.7.15rc1 and Python 3.6.6, numpy 1.13.3

Comments

16

Maybe a bit hacky, but I just slice them off after using np.array2string so:

import numpy as np

a = np.arange(0,10)
a_str = np.array2string(a, precision=2, separator=', ')
print(a_str[1:-1])

Result:

    0, 1, 2, 3, 4, 5, 6, 7, 8, 9

np.array2string has lots of options also, so you can set your column width which can be very helpful with lots of data:

a = np.arange(0,15)
a_str = np.array2string(a, precision=2, separator=', ', max_line_width=15)
print(' ' + a_str[1:-1])

Gives:

       0,  1,  2,
       3,  4,  5,
       6,  7,  8,
       9, 10, 11,
      12, 13, 14

And it will smartly split at the array elements. Note the space appended to the beginning of the string to account for aligning the first row after removing the initial bracket.

Comments

5

If you have a numpy array to begin with rather than a list (since you mention a "real numpy array" in your post) you could use re.sub on the string representation of the array:

print(re.sub('[\[\]]', '', np.array_str(a)))

Again, this is assuming your array a was a numpy array at some point. This has the advantage of working on matrices as well.

Comments

4

Numpy provides two functions for this array_str and array_repr -- either of which should fit your needs. Since you could use either, here's an example of each:

>>> from numpy import arange, reshape, array_str
>>> M = arange(10).reshape(2,5)
>>> M
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> array_str(M)
'[[0 1 2 3 4]\n [5 6 7 8 9]]'
>>> array_repr(M)
'array([[0, 1, 2, 3, 4],\n       [5, 6, 7, 8, 9]])'

These two functions are both highly optimized and, as such, should be preferred over a function you might write yourself. When dealing with arrays this size, I'd imagine you'd want all the speed you can get.

2 Comments

Using build-in functions is definitely of advantage, but it still leaves the brackets in. So this method superior for other, but similar, cases. +1
You said you need save the string to a file. If you have plans on later retrieving the string from that file it could be useful to have the brackets. Also, a combination of sub-strings and splits() would remove the brackets.
4
>>> a=np.array([1,2,3,4,5])
>>> print(*a)
1 2 3 4 5

>>> print(str(a)[1:-1])
1 2 3 4 5

same with lists

1 Comment

The str() will not work when the length of the array is long. np.array2string is an alternative.
3

If you are dealing with floating-point numbers and two dimensional arrays you can also do the following:

import numpy as np
np.random.seed(77)

def my_print(x):
    for row in x:
        print(' '.join(map(lambda x: "{:.3f}\t".format(x), row)))

if __name__ == '__main__':
    x = np.random.random(size=(3, 9))
    my_print(x)

which prints:

0.919    0.642   0.754   0.139   0.087   0.788   0.326   0.541   0.240  
0.545    0.401   0.715   0.837   0.588   0.296   0.281   0.706   0.423  
0.057    0.747   0.452   0.176   0.049   0.292   0.067   0.751   0.064

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.