0

I receive strings as follows that I need to save and then convert back to numpy arrays later

[0.46619281 -0.79148525  0.20800316 -0.16633733  1.53767002]
[ 0.53119281 -0.79148525  0.20800316 -0.16633733  1.53762345 ]

Note how the second line has a space after the first [ and before the last ]

How can I format the string to change it so that it does not have this space before and after the brackets?

I need a consistent way to store the arrays as strings so I can then convert them back again as detailed in this post: Convert string containg array of floats to numpy array

Harry Boy
  • 4,159
  • 17
  • 71
  • 122

2 Answers2

0
a = s.replace('[','').replace(']','').split()
a = list(map(int, a))
  • This creates class 'list'>: [0.53119281, -0.79148525, 0.20800316, -0.16633733, 1.53762345] where there are commas between numbers. How can get it as a string similar to my examples? – Harry Boy Sep 19 '19 at 13:15
0

The best professional step is to enforce the sources, that "produce" the different strings, to re-factor their code so as to uniformly adhere to your defined API for string-representation of array(s).

If you trust the sources and want to rely on un-coordinated formats, use an explicit ex-post transformation:

>>> "[ ............ ] [....... ]".replace( "[ ", "[" ).replace( " ]", "]" )
'[............] [.......]'
user3666197
  • 1
  • 6
  • 50
  • 92