0

I have a string like this -99.00 -99.00 99.00 9.00 -99.00 and I want to convert all the numbers inside the string to float values and then append them to an array, how could I achieve that? Between the values 99.00 and 9.00 there are 3 white spaces separating them .

The append part I would be able to do by myself if knew how to convert the values one by one.

Andy G
  • 19,232
  • 5
  • 47
  • 69
i'mlaguiar
  • 21
  • 2
  • 7

2 Answers2

4

A pythonic way to do this is using a list comprehension and split

my_string = '-99.00 -99.00 99.00 9.00 -99.00'
arr = [float(x) for x in my_string.split(' ')]
print(arr)

Output:

[-99.0, -99.0, 99.0, 9.0, -99.0]
user3483203
  • 50,081
  • 9
  • 65
  • 94
1

You can use the split and map method

a =  '-99.00 -99.00 99.00 9.00 -99.00' 
print map(float, a.split(" "))

Result:

[-99.0, -99.0, 99.0, 9.0, -99.0]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Using `map` when on py3 could be more efficient, depending on the input string and the poster's usage. This is due to `map` becoming a lazy generator, as opposed to it generating the whole list up front. Granted string split doesn't do that. – jheld Jan 18 '18 at 13:34