注意:尽管链接的重复项不是重复项(它明确询问要分别转换为int和float),但我仍将其标记为重复项,因为它包含有关该主题的出色信息(以及与我的解决方案类似的答案)
摘要:我正在寻找一种将字符串转换为数字(整数或浮点数)的pythonic方法。
我目前使用瀑布函数,但在起作用时,在美学上并不特别令人满意:
def convert_to_int_or_float(a):
# maybe an integer
try:
return int(a)
except ValueError:
# nope - so can be a float or a str
try:
return float(a)
except ValueError:
# must be a str
return a
for s in ["0", "12", "-13", "14.7", "-14.7", "hello"]:
print(s, type(convert_to_int_or_float(s)))
# outputs
# 0 <class 'int'>
# 12 <class 'int'>
# -13 <class 'int'>
# 14.7 <class 'float'>
# -14.7 <class 'float'>
# hello <class 'str'>
有更好的方法吗?(最好是一个模块)
我看了看,math
但没找到任何东西。
一种方法是使用ast
模块
例如:
import ast
def convert_to_int_or_float(a):
try:
return ast.literal_eval(a)
except ValueError:
return a
for s in ["0", "12", "-13", "14.7", "-14.7", "hello"]:
print(s, type(convert_to_int_or_float(s)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句