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.
-
:Check this http://stackoverflow.com/questions/5365520/numpy-converting-array-from-float-to-strings – George Feb 20 '12 at 11:13
-
3Are you sure you really need a string representation for that big array? What for? – Feb 20 '12 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`. – Framester Feb 20 '12 at 11:21
-
2The real question is why on earth doesn't np.array2string have an option to suppress the brackets. – daknowles Jun 11 '19 at 00: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...? – smci Mar 15 '20 at 04:02
7 Answers
You can use the join
method from string:
>>> a = [1,2,3,4,5]
>>> ' '.join(map(str, a))
"1 2 3 4 5"

- 12,990
- 1
- 55
- 75
-
thanks, I tried `join` unsuccessfully before. `Map` is the missing piece for me. – Framester Feb 20 '12 at 12:40
-
7a simpler variant (IMHO) would be with an iterator: `' '.join(str(n) for n in a)` – alexis Feb 20 '12 at 16:03
-
Something like this looks good: def float2str(f): return '{:.5f}'.format(f) ' '.join(map(float2str, embeddings_fb.embed_token('.'))) – ben26941 Apr 25 '19 at 09:45
-
@tito Is there any fast alternative to do the same thing. It is very slow for a big array. – shaifali Gupta May 17 '19 at 07:51
-
@shaifaliGupta Printing is more bounded by I/O than CPU so I doubt alternative methods are going to be much faster. – Mateen Ulhaq Feb 26 '21 at 04:10
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

- 347,512
- 102
- 1,199
- 985
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.

- 161
- 1
- 4
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.

- 1,332
- 1
- 10
- 11
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.

- 395
- 2
- 10
-
2Using build-in functions is definitely of advantage, but it still leaves the brackets in. So this method superior for other, but similar, cases. +1 – Framester Feb 20 '12 at 12:44
-
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. – mau5padd Feb 20 '12 at 13:38
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

- 3,282
- 3
- 47
- 83
>>> 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

- 303
- 1
- 7
-
The str() will not work when the length of the array is long. np.array2string is an alternative. – ZK xxxxx Jan 19 '21 at 19:24