Say we have an numpy.ndarray with numpy.str_ elements. For example, below arr is the numpy.ndarray with four numpy.str_ elements like this:
>>> print(arr)
['\tSTART\t 0\n' '12345 ABCDEFG' '1A 2B3C' '\nE N D']
Is there a way I can write the contents of arr
to a file without the [
, ]
and without the '
for each numpy.str_
element?
That is, to write arr
like this:
\tSTART\t 0\n12345 ABCDEFG1A 2B3\nE N D
Also, can I print the elements of the numpy
array one element per line? Ideally, here as well without the [
, ]
and without the '
.
That is, to print arr
like this:
\tSTART\t 0\n
12345 ABCDEFG
1A 2B3
\nE N D
EDIT
(1) If try this
with open(resultfile, 'w') as f:
f.write(str(arr))
I get
['\tSTART\t 0\n' '12345 ABCDEFG' '1A 2B3C' '\nE N D']
(2) If I try this (as suggested by GreenHawk1220's answer)
A = str('\n'.join(arr))
B = ''.split(A)
del B[0]
# del B[-1] #Deletes end characters # *THIS GIVES INDEXERROR*
C = ''.join(B)
print(C)
with open(resultfile, 'w') as f:
f.write(C)
I get nothing (and nothing is writtent to the file).
Make the array:
Join into one string; equivalent of
''.join(arr.tolist())
(actually''.join(list(arr))
)The
print/str
representation expands on the\n
and\t
.the
repr
quotes them:f.write
has the same issues:This isn't really a string array issue. It's a question of how to print/write a string that contains
\n
and\t
.Following the comment:
and for the individual strings:
Just in case it isn't obvious, I'm using Ipython with Py3. Py2 might be different.
The
encode
creates a bytestring with extra\\t
etc..decode
can be used to turn it back into unicode for neat printing: