SH92
SH92

Reputation: 13

How to convert a string to a float in python?

I have the following code:

invoer = file_input().split("=")
fileinput=[float(i.replace(',', '.')) + 1 for i in invoer] 

where invoer is:

>>> print invoer
['5,4 4,5 8,7', '6,3 3,2 9,6 4,3', '7,6', '9,8', '5,5 7,8 6,5 6,4']

However I cannot seem to get this in to a float.

Upvotes: 0

Views: 154

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121644

You have multiple numbers per string, so you'll need to split those on whitespace first:

[float(i.replace(',', '.')) + 1 for s in invoer for i in s.split()] 

In a list comprehension sequential for loops should be read as nested loops; the outer loop is for s in invoer, then for each s we loop over for i in s.split(). Each i in that loop is converted to a float, then incremented by 1.

Demo:

>>> invoer = ['5,4 4,5 8,7', '6,3 3,2 9,6 4,3', '7,6', '9,8', '5,5 7,8 6,5 6,4']
>>> [float(i.replace(',', '.')) + 1 for s in invoer for i in s.split()] 
[6.4, 5.5, 9.7, 7.3, 4.2, 10.6, 5.3, 8.6, 10.8, 6.5, 8.8, 7.5, 7.4]

Upvotes: 1

Related Questions