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
2

3 Answers 3

3

You can try stripping letters from your input:

from string import ascii_lowercase

b='56.78 ab'
float(b.strip(ascii_lowercase))
Sign up to request clarification or add additional context in comments.

2 Comments

If you put in an input like b='56.78 ab#$', this does not work.
@ToClickorNottoClick, the question did say 'other letters', so the solution will work.
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

1 Comment

This would be the other solution that I would propose.
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'
>>> 

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.