将字符串转换为python中的浮子,int和弦
我已经调用一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
isInstance()
:输出:
Try using
isinstance()
:Output:
这是快速和折扣的东西,只需尝试将其转换为
int
或float
(在此顺序),如果所有其他方法都失败了,只需返回您所拥有的内容即可。如果您没有字符串,请确保尽早返回(因此,它是int
或float
)以避免转换数字类型。Here's something quick-and-dirty, just try to convert to
int
orfloat
(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 isint
orfloat
already) to avoid converting numeric types.检查
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.我认为
ast.literal_eval
是正确的选项I think
ast.literal_eval
is the right option here