1

I need to convert some strings to float. Most of them are only numbers but some of them have letters too. The regular float() function throws an error.

a='56.78'
b='56.78 ab'

float(a) >> 56.78
float(b) >> ValueError: invalid literal for float()

One solution is to check for the presence of other characters than numbers, but I was wondering if there is some built-in or other short function which gives:

magicfloat(a) >> 56.78
magicfloat(b) >> 56.78
csaladenes
  • 1,100
  • 1
  • 11
  • 27
  • http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python – Reticulated Spline Nov 11 '14 at 05:30
  • possible duplicate of [Strip all non-numeric characters (except for ".") from a string in Python](http://stackoverflow.com/questions/947776/strip-all-non-numeric-characters-except-for-from-a-string-in-python) – Andy Nov 11 '14 at 05:31

3 Answers3

3

You can try stripping letters from your input:

from string import ascii_lowercase

b='56.78 ab'
float(b.strip(ascii_lowercase))
vikramls
  • 1,802
  • 1
  • 11
  • 15
2

use a regex

import re

def magicfloat(input):
    numbers = re.findall(r"[-+]?[0-9]*\.?[0-9]+", input)

    # TODO: Decide what to do if you got more then one number in your string
    if numbers:
        return float(numbers[0])

    return None

a=magicfloat('56.78')
b=magicfloat('56.78 ab')

print a
print b

output:

56.78
56.78
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
0

Short answer: No.

There is no built-in function that can accomplish this.

Longish answer: Yes:

One thing you can do is go through each character in the string to check if it is a digit or a period and work with it from there:

def magicfloat(var):
    temp = list(var)
    temp = [char for char in temp if char.isdigit() or char == '.']
    var = "".join(temp)
    return var

As such:

>>> magicfloat('56.78 ab')
'56.78'
>>> magicfloat('56.78')
'56.78'
>>> magicfloat('56.78ashdusaid')
'56.78'
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76