简体   繁体   中英

Converting strings into floats, int and strings in Python

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

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM