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?

7
  • What do you think would \r or \n become when converted to a float? Commented Mar 23, 2015 at 20:15
  • sorry, I did use strip as well, but that does not help Commented Mar 23, 2015 at 20:15
  • edited question to reflect use of strip Commented Mar 23, 2015 at 20:15
  • It's probably worth noting that a.strip() on its own does nothing. You have to do something with the result, ex. a = a.strip() or x = float(a.strip()) or whatever. Commented Mar 23, 2015 at 20:20
  • how do you get such a string? Commented Mar 23, 2015 at 20:20

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

or use a.strip("\r\n\t '") to reduce this to one strip call.
2

You can also use str.translate:

print(float(a.translate(None,"\r\n'")))

Comments

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])

1 Comment

The only issue with this is it can't do it again and again, you need to know what you are slicing before hand.
1

Remove everything but digit and dot

>>> a = "'92.345123'\r\n\r\n"
>>> float(re.sub(r'[^0-9\.]', '', a))
92.345123

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.