Convert string to int, float or leave it as string, depending on the best option

Viewed 185

I'm trying to handle a dataset containing only str, but the values of the str can be either real text or something like "1.0" and "3.54".

I want to convert all string to the best possible type, which means 1.0 should be converted to int, 3.54 should be converted to float and everything else should stay str.

What is the best way to do so?

4 Answers

lets try

def convert(txt):
try:
    k = float(txt)
    if k%1 ==0:
        return int(k)
    return k

except ValueError:
    return txt

now what I'm thinking is, the input is either a number or not, anyway we can float it. if it is also divisable by 1 its an int and we're done. if it isn't then it is a float after all and we're done. any other case: there's nothing that we can do, and then let's return it

You can use a try except block to perform the operation.

for s in string:
    try:
        //convert to int or float
    except:
        pass

You may use

strings = ["some weird junk", "1.0", "2.345", -1000]

for string in strings:
    try:
        number, decimal = string.split(".")
        try:
            if decimal == "0":
                value = int(number)
            else:
                value = float(string)
        except:
            value = string
    except (ValueError, AttributeError):
        try:
            value = int(string)
        except ValueError:
            value = string

    print(value, type(value))

Which yields

some weird junk <class 'str'>
1 <class 'int'>
2.345 <class 'float'>
-1000 <class 'int'>
def convert(string):
    possible = [str, int, float]
    for func in possible:
        try:
            result = func(string)
        except ValueError:
            continue
        if str(result) == string and type(result) is not str:
            return result
    return string

strings = ['hello', '1', '1.0', '1.9']
for string in strings:
   result = convert(string)
   print(type(result), result)
Output:
<class 'str'> hello
<class 'int'> 1
<class 'float'> 1.0
<class 'float'> 1.9
Related