如何将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中)自动转换类型。
当前回答
这个问题似乎有点过时了。但让我建议一个函数parseStr,它有类似的功能,即返回整数或浮点数,如果给定的ASCII字符串不能转换为任何一个,它将不受影响地返回。当然,代码可能会被调整为只执行您想要的操作:
>>> import string
>>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
... int(x) or x.isalnum() and x or \
... len(set(string.punctuation).intersection(x)) == 1 and \
... x.count('.') == 1 and float(x) or x
>>> parseStr('123')
123
>>> parseStr('123.3')
123.3
>>> parseStr('3HC1')
'3HC1'
>>> parseStr('12.e5')
1200000.0
>>> parseStr('12$5')
'12$5'
>>> parseStr('12.2.2')
'12.2.2'
其他回答
float(x) if '.' in x else int(x)
Python2方法检查字符串是否为浮点:
def is_float(value):
if value is None:
return False
try:
float(value)
return True
except:
return False
有关is_float的Python3版本,请参见:检查字符串是否可以在Python中转换为float
此函数的较长且更准确的名称可以是:is_converable_to_float(value)
Python中的浮点数是什么,不是什么,可能会让您感到惊讶:
以下单元测试是使用python2完成的。检查Python3对于哪些字符串可以转换为浮点,有不同的行为。一个令人困惑的区别是,现在允许任意数量的内部下划线:(float(“1_3.4”)==float(13.4))为True
val is_float(val) Note
-------------------- ---------- --------------------------------
"" False Blank string
"127" True Passed string
True True Pure sweet Truth
"True" False Vile contemptible lie
False True So false it becomes true
"123.456" True Decimal
" -127 " True Spaces trimmed
"\t\n12\r\n" True whitespace ignored
"NaN" True Not a number
"NaNanananaBATMAN" False I am Batman
"-iNF" True Negative infinity
"123.E4" True Exponential notation
".1" True mantissa only
"1_2_3.4" False Underscores not allowed
"12 34" False Spaces not allowed on interior
"1,234" False Commas gtfo
u'\x30' True Unicode is fine.
"NULL" False Null is not special
0x3fade True Hexadecimal
"6e7777777777777" True Shrunk to infinity
"1.797693e+308" True This is max value
"infinity" True Same as inf
"infinityandBEYOND" False Extra characters wreck it
"12.34.56" False Only one dot allowed
u'四' False Japanese '4' is not a float.
"#56" False Pound sign
"56%" False Percent of what?
"0E0" True Exponential, move dot 0 places
0**0 True 0___0 Exponentiation
"-5e-5" True Raise to a negative number
"+1e1" True Plus is OK with exponent
"+1e1^5" False Fancy exponent not interpreted
"+1e1.3" False No decimals in exponent
"-+1" False Make up your mind
"(1)" False Parenthesis is bad
你以为你知道什么是数字吗?你没有你想象的那么好!没什么奇怪的。
不要在生命关键型软件上使用此代码!
通过这种方式捕获广泛的异常,杀死金丝雀并吞食异常,产生一个很小的机会,即有效的float as字符串将返回false。float(…)行代码可能由于一千种与字符串内容无关的原因而失败。但如果你用Python这样的鸭子型原型语言编写生命关键型软件,那么你会遇到更大的问题。
处理十六进制、八进制、二进制、十进制和浮点
这个解决方案将处理数字的所有字符串约定(我所知道的)。
def to_number(n):
''' Convert any number representation to a number
This covers: float, decimal, hex, and octal numbers.
'''
try:
return int(str(n), 0)
except:
try:
# Python 3 doesn't accept "010" as a valid octal. You must use the
# '0o' prefix
return int('0o' + n, 0)
except:
return float(n)
这个测试用例输出说明了我所说的内容。
======================== CAPTURED OUTPUT =========================
to_number(3735928559) = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0") = 0 == 0
to_number(100) = 100 == 100
to_number("42") = 42 == 42
to_number(8) = 8 == 8
to_number("0o20") = 16 == 16
to_number("020") = 16 == 16
to_number(3.14) = 3.14 == 3.14
to_number("2.72") = 2.72 == 2.72
to_number("1e3") = 1000.0 == 1000
to_number(0.001) = 0.001 == 0.001
to_number("0xA") = 10 == 10
to_number("012") = 10 == 10
to_number("0o12") = 10 == 10
to_number("0b01010") = 10 == 10
to_number("10") = 10 == 10
to_number("10.0") = 10.0 == 10
to_number("1e1") = 10.0 == 10
下面是测试:
class test_to_number(unittest.TestCase):
def test_hex(self):
# All of the following should be converted to an integer
#
values = [
# HEX
# ----------------------
# Input | Expected
# ----------------------
(0xDEADBEEF , 3735928559), # Hex
("0xFEEDFACE", 4277009102), # Hex
("0x0" , 0), # Hex
# Decimals
# ----------------------
# Input | Expected
# ----------------------
(100 , 100), # Decimal
("42" , 42), # Decimal
]
values += [
# Octals
# ----------------------
# Input | Expected
# ----------------------
(0o10 , 8), # Octal
("0o20" , 16), # Octal
("020" , 16), # Octal
]
values += [
# Floats
# ----------------------
# Input | Expected
# ----------------------
(3.14 , 3.14), # Float
("2.72" , 2.72), # Float
("1e3" , 1000), # Float
(1e-3 , 0.001), # Float
]
values += [
# All ints
# ----------------------
# Input | Expected
# ----------------------
("0xA" , 10),
("012" , 10),
("0o12" , 10),
("0b01010" , 10),
("10" , 10),
("10.0" , 10),
("1e1" , 10),
]
for _input, expected in values:
value = to_number(_input)
if isinstance(_input, str):
cmd = 'to_number("{}")'.format(_input)
else:
cmd = 'to_number({})'.format(_input)
print("{:23} = {:10} == {:10}".format(cmd, value, expected))
self.assertEqual(value, expected)
我用这个函数
import ast
def parse_str(s):
try:
return ast.literal_eval(str(s))
except:
return
它会将字符串转换为其类型
value = parse_str('1') # Returns Integer
value = parse_str('1.5') # Returns Float
对于数字和字符:
string_for_int = "498 results should get"
string_for_float = "498.45645765 results should get"
首次导入重新:
import re
# For getting the integer part:
print(int(re.search(r'\d+', string_for_int).group())) #498
# For getting the float part:
print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765
对于简单的模型:
value1 = "10"
value2 = "10.2"
print(int(value1)) # 10
print(float(value2)) # 10.2