Mark
Mark

Reputation: 389

How to change array of floats to array of strings, then save to txt

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?

Upvotes: 1

Views: 109

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

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")

Upvotes: 3

Related Questions