Given a list of strings
['2.13', '4.67', '-6.1']
is there a way to convert this list into a list of floats?
Given a list of strings
['2.13', '4.67', '-6.1']
is there a way to convert this list into a list of floats?
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
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))