将字符串转换为python中的浮子,int和弦

发布于 2025-01-26 00:34:57 字数 811 浏览 3 评论 0原文

我已经调用一个API,有时会以字符串格式返回我的数值,“ 288”而不是288“ 0.1523”而不是0.1513其他时间,我获得了适当的数值值,39。我还得到了“ Hello”之类的字符串。

我需要一个以适当格式转换所有输入的函数。这意味着:

  • 如果我得到“ 288”将其转换为整数:288
  • 如果我得到“ 0.323”将其转换为float:0.323
  • 如果我得到288将其保持原样(已经是整数)。
  • 如果我得到0.323离开时(它已经是一个浮点)。
  • 如果我得到“ Hello”离开原样。

这是我的尝试。问题是,这也将我所有的浮子转换为整数,我不想要这个。当字符串是字符串本身时,这也不起作用(“ Hello”)。有人可以给我手吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

棒棒糖 2025-02-02 00:34:57

尝试使用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.

输出:

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

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
筱果果 2025-02-02 00:34:57

这是快速和折扣的东西,只需尝试将其转换为intfloat(在此顺序),如果所有其他方法都失败了,只需返回您所拥有的内容即可。如果您没有字符串,请确保尽早返回(因此,它是intfloat)以避免转换数字类型。

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

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
痴意少年 2025-02-02 00:34:57

检查value是否包含,如果它确实尝试将其转换为float,否则尝试将其转换为int,如果没有工作,则只需返回值。

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.

倒带 2025-02-02 00:34:57

我认为ast.literal_eval是正确的选项

from ast import literal_eval

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文