Home > Software engineering >  Converting strings into floats, int and strings in Python
Converting strings into floats, int and strings in Python

Time:05-05

I've to call an API that sometimes returns me numerical values in string format, "288" instead of 288, or "0.1523" instead of 0.1513. Some other times, I get the proper numerical value, 39. I also get strings like "HELLO".

I need a function that converts all the inputs in its proper format. This means:

  • If I get "288" convert it to an integer: 288.
  • If I get "0.323" convert it to a float: 0.323.
  • If I get 288 leave it as it is (its an integer already).
  • If I get 0.323 leave as it is (its a float already).
  • If I get "HELLO" leave as it is.

This is my try. The thing is that this also converts me all the floats into integers, and I don't want this. This also doesn't work when the string is a string itself ("HELLO"). Can someone give me hand?

def parse_value(value):
    try:
       value = int(value)
    except ValueError:
        try:
            value = float(value)
        except ValueError:
            pass
    return value

CodePudding user response:

Try using isinstance():

def parse_value(value):
    if isinstance(value, str): # Check if the value is a string or not
        if value.isnumeric(): # Checks if the value is an integer(in the form of a string)
            return int(value)# Returns int of value
        else:
            try:
                return float(value) # Returns the float of that value
            except ValueError: # Incase it's not a float return string
                pass
    return value # return the value as it is if it's not a string.

Output:

parse_value('12.5')
12.5
parse_value('12')
12
parse_value('hello')
'hello'
parse_value(12)
12
parse_value(12.5)
12.5

CodePudding user response:

Here's something quick-and-dirty, just try to convert to int or float (in that order), if all else fails, just return what you had. Make sure to return early if you don't have a string (so then it is int or float already) to avoid converting numeric types.

def parse(x):
    if not isinstance(x, str):
        return x
    for klass in int, float:
        try:
            return klass(x)
        except ValueError:
            pass
    return x

CodePudding user response:

Check if value contains a ., if it does try converting it to a float, otherwise try converting it to an int, if neither works just return the value.

CodePudding user response:

I think ast.literal_eval is the right option here

from ast import literal_eval

def eval_api(val):
    try:
        return literal_eval(val)
     except NameErrpr:
        Return val
  • Related