0

Given a list of strings

['2.13', '4.67', '-6.1']

is there a way to convert this list into a list of floats?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Kieran
  • 13
  • 2
  • 4
    convert it when you read it from the file using the `float` function – Paul H Apr 05 '21 at 15:24
  • Also you can iterate directly on the `filehandle` to go over the file line-by-line. You should be sure to check for if the line is empty as well, because may programs will end the file with a blank line. – Aaron Apr 05 '21 at 15:29
  • `list(map(float, list_of_strings))` – Paul H Apr 05 '21 at 15:45

3 Answers3

1

You can convert strings into floats using float(string_value).

>>> value = '3.14159'
>>> float(value)
3.14159

Edit: some more info:

Note that if string_value is not a valid float, Python will raise a ValueError:

>>> value = 'not a float'
>>> float(value)
ValueError: could not convert string to float: 'not a float'

So if there's a chance your file has invalid values in it, it may be worth doing:

try:
    float_value = float(value)
except ValueError:
    # Handle errors here
Dave
  • 327
  • 1
  • 7
-1
my_float_list = list(map(float, ['2.13', '4.67', '-6.1']))

Relevant docs:

  1. map
  2. float
  3. list
Asker
  • 1,299
  • 2
  • 14
  • 31
-2

Try this simple loop:

my_string_list = ['2.13', '4.67', '-6.1']
my_float_list = []
for item in my_string_list:
    my_float_list.append(float(item))
Frightera
  • 4,773
  • 2
  • 13
  • 28