如何将str转换为float?"545.2222" → 545.2222如何将str转换为int?"31" → 31
相反,请参见在Python中将整数转换为字符串和将浮点转换为字符串而不舍入。
请改为使用“如何将输入读取为数字?”?关闭重复问题,其中OP从用户输入中接收到字符串并立即想要转换它,或者希望输入(在3.x中)自动转换类型。
如何将str转换为float?"545.2222" → 545.2222如何将str转换为int?"31" → 31
相反,请参见在Python中将整数转换为字符串和将浮点转换为字符串而不舍入。
请改为使用“如何将输入读取为数字?”?关闭重复问题,其中OP从用户输入中接收到字符串并立即想要转换它,或者希望输入(在3.x中)自动转换类型。
当前回答
如果您正在处理混合整数和浮点数,并希望以一致的方式处理混合数据,下面是我使用正确的docstring的解决方案:
def parse_num(candidate):
"""Parse string to number if possible
It work equally well with negative and positive numbers, integers and floats.
Args:
candidate (str): string to convert
Returns:
float | int | None: float or int if possible otherwise None
"""
try:
float_value = float(candidate)
except ValueError:
return None
# Optional part if you prefer int to float when decimal part is 0
if float_value.is_integer():
return int(float_value)
# end of the optional part
return float_value
# Test
candidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']
res_list = list(map(parse_num, candidates))
print('Before:')
print(candidates)
print('After:')
print(res_list)
输出:
Before:
['34.77', '-13', 'jh', '8990', '76_3234_54']
After:
[34.77, -13, None, 8990, 76323454]
其他回答
将字符串传递给此函数:
def string_to_number(str):
if("." in str):
try:
res = float(str)
except:
res = str
elif(str.isdigit()):
res = int(str)
else:
res = str
return(res)
它将根据传递的内容返回int、float或string。
int字符串
print(type(string_to_number("124")))
<class 'int'>
浮点数字符串
print(type(string_to_number("12.4")))
<class 'float'>
字符串
print(type(string_to_number("hello")))
<class 'str'>
看起来像浮点数的字符串
print(type(string_to_number("hel.lo")))
<class 'str'>
float(“545.2222”)和int(float(”545.2222“))
要在Python中进行类型转换,请使用该类型的构造函数,将字符串(或您试图转换的任何值)作为参数传递。
例如:
>>>float("23.333")
23.333
在幕后,Python正在调用对象__float__方法,该方法应返回参数的float表示。这特别强大,因为您可以使用__float__方法定义自己的类型(使用类),以便使用float(myobject)将其强制转换为float。
def num(s):
"""num(s)
num(3),num(3.7)-->3
num('3')-->3, num('3.7')-->3.7
num('3,700')-->ValueError
num('3a'),num('a3'),-->ValueError
num('3e4') --> 30000.0
"""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise ValueError('argument is not a string of number')
Use:
def num(s):
try:
for each in s:
yield int(each)
except ValueError:
yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()
这是我所能想到的最具Python风格的方式。