5

I have a string that looks like this:

a = "'92.345'\r\n\r\n"
a.strip()

When I try to convert it into float using np.float(a) or just float(a), I get

*** Value error: could not convert string to float: '92.345'

How do I convert it cleanly to a float?

user308827
  • 21,227
  • 87
  • 254
  • 417

4 Answers4

7

You need to strip your string to remove the whitespaces and one quote ':

>>> float(a.strip().strip("'"))
92.345

Or as @Martijn Pieters says in comment you can use use a.strip("\r\n\t '") to reduce this to one strip call.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
2

You can also use str.translate:

print(float(a.translate(None,"\r\n'")))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

Try slicing the string to extract only the digit part of it:

a = "'92.345'\r\n\r\n"
x = float(a[1:6])
Mazdak
  • 105,000
  • 18
  • 159
  • 188
NevDev
  • 604
  • 5
  • 8
  • The only issue with this is it can't do it again and again, you need to know what you are slicing before hand. – Zizouz212 Mar 23 '15 at 20:17
1

Remove everything but digit and dot

>>> a = "'92.345123'\r\n\r\n"
>>> float(re.sub(r'[^0-9\.]', '', a))
92.345123
Heisenberg
  • 1,500
  • 3
  • 18
  • 35