Raymond Chenon
Raymond Chenon

Reputation: 12682

Python3 most efficient String to Float conversion

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

Answers (2)

Muhammad Usman
Muhammad Usman

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:

  1. Replace the empty space with nothing
  2. Replace the comma with a dot
  3. Convert string to float

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

wim
wim

Reputation: 362786

You may drop the whitespace stripping. float will eat up whitespace:

>>> float('   0.18')
0.18

Upvotes: 3

Related Questions