1

I know this question is addressed here: Numpy converting array from float to strings, but I am having trouble with the implementation.

A=np.array([57/13, 7/5, 6/8])
B=A.astype('|S4' )

yields array([b'4.38',b'1.4', b'0.75]). The b's remain when I save to txt.

np.savetxt('my_file.txt', B, fmt="%s")

The issue of why the b's are there is discussed here: What does the 'b' character do in front of a string literal?, but with no explanation for how to get rid of them. Any help?

Also, is there any way to get rid of the ' ' around each string when printing?

Community
  • 1
  • 1
Mark
  • 389
  • 1
  • 7
  • 19
  • `savetxt` `fmt` gives you more formatting control than `astype`. Try `np.savetxt('myfile.txt',A,fmt='%.2f')` – hpaulj Jul 22 '15 at 07:08

1 Answers1

3

From documentation -

'S', 'a' - (byte-)string

'U' - Unicode

S is for Byte-String, hence the b infront.

You should use U instead for unicode strings, and then save it to text.

Example -

A=np.array([57/13, 7/5, 6/8])
B=A.astype('U4')

np.savetxt('my_file.txt', B, fmt="%s")
Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176