Reputation: 12682
I extract data from scrapy . There is a string representing a float ' 0,18' . What is the most efficient way to convert a String into a float ?
Right now, I convert like this. There are space characters to remove. Comma is replaced by dot.
>>> num = ' 0,18'
>>> float(num.replace(' ','').replace(',','.'))
0.18
I believe my method is far from efficient in time complexity when dealing with tons of data.
Upvotes: 1
Views: 1018
Reputation: 215
This is okay but if you look at how this is processed, at a high level, there are three function calls, every time:
To simply reduce code, you can get rid of step 1. And just replace the comma with the dot and then convert the string to float.
Upvotes: 1
Reputation: 362786
You may drop the whitespace stripping. float
will eat up whitespace:
>>> float(' 0.18')
0.18
Upvotes: 3