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?

1
  • savetxt fmt gives you more formatting control than astype. Try np.savetxt('myfile.txt',A,fmt='%.2f') Commented Jul 22, 2015 at 7:08

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! You are the best.

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.