- 如何将
str
转换为float
?
"545.2222" → 545.2222
如何将 str
转换为 int
?"31" → 31
反向操作,请参见如何将整数转换为字符串(Python)和如何将浮点数转换为不四舍五入的字符串(Python)。
请改用如何将输入读取为数字?来关闭重复提问,其中提问者从用户输入中接收到字符串,并立即希望进行转换,或者希望在3.x版本中使用input
自动转换类型。
str
转换为 float
?"545.2222" → 545.2222
如何将 str
转换为 int
?"31" → 31
反向操作,请参见如何将整数转换为字符串(Python)和如何将浮点数转换为不四舍五入的字符串(Python)。
请改用如何将输入读取为数字?来关闭重复提问,其中提问者从用户输入中接收到字符串,并立即希望进行转换,或者希望在3.x版本中使用input
自动转换类型。
处理十六进制、八进制、二进制、十进制和浮点数
此解决方案将处理数字的所有字符串约定(我所知道的全部约定)。
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)
a = int(float(a)) if int(float(a)) == float(a) else float(a)
这段代码试图解析一个字符串,并根据字符串代表的内容返回int
或float
。它可能会引发解析异常或出现一些意外行为。
def get_int_or_float(v):
number_as_float = float(v)
number_as_int = int(number_as_float)
return number_as_int if number_as_float == number_as_int else
number_as_float
如果你需要处理混合整数和浮点数,并且想要一种处理混合数据的一致方法,那么这里是我的解决方案,附带适当的文档字符串:
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 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()
这是我能想到的最Pythonic的方式。
def string_to_int_or_float(s):
try:
f = float(s) # replace s with str(s) if you are not sure that s is a string
except ValueError:
print("Provided string '" + s + "' is not interpretable as a literal number.")
raise
try:
i = int(str(f).rstrip('0').rstrip('.'))
except:
return f
return i
它可能不是最快的,但它正确处理了字面数字,而许多其他解决方案则失败,例如:
>>> string_to_int_or_float('789.')
789
>>> string_to_int_or_float('789.0')
789
>>> string_to_int_or_float('12.3e2')
1230
>>> string_to_int_or_float('12.3e-2')
0.123
>>> string_to_int_or_float('4560e-1')
456
>>> string_to_int_or_float('4560e-2')
45.6
s = '542.22'
f = float(s) # This converts string data to float data with a decimal point
print(f)
i = int(f) # This converts string data to integer data by just taking the whole number part of it
print(i)
想了解更多关于解析数据类型的信息,请查看Python文档!
def conv_to_num(x, num_type='asis'):
'''Converts an object to a number if possible.
num_type: int, float, 'asis'
Defaults to floating point in case of ambiguity.
'''
import numbers
is_num, is_str, is_other = [False]*3
if isinstance(x, numbers.Number):
is_num = True
elif isinstance(x, str):
is_str = True
is_other = not any([is_num, is_str])
if is_num:
res = x
elif is_str:
is_float, is_int, is_char = [False]*3
try:
res = float(x)
if '.' in x:
is_float = True
else:
is_int = True
except ValueError:
res = x
is_char = True
else:
if num_type == 'asis':
funcs = [int, float]
else:
funcs = [num_type]
for func in funcs:
try:
res = func(x)
break
except TypeError:
continue
else:
res = x
如果您想将类型更改为其他数据类型,则可以使用显式类型转换,这意味着您必须使用 int()
将字符串类型更改为 integer
,并使用 float()
将其更改为 float
类型。
但是,如果我们深入了解类型转换的概念,我们会意识到,除非必要,否则类型转换不是程序员的好选择,因此我们应该仅在需要时才使用类型转换,例如当您使用输入函数输入用户输入值时。
额外提示:您还可以使用类型转换将 tuple
转换为 list
,然后将它们转换回 tuple
,从而可以对不可变数据类型 tuple
进行更改(list()
和 tuple()
是相应的函数)。
通过使用 int 和 float 方法,我们可以将字符串转换为整数和浮点数。
s="45.8"
print(float(s))
y='67'
print(int(y))
type(my_object)
。结果通常可以作为函数调用来执行转换。例如,type(100)
的结果是int
,因此你可以调用int(my_object)
来尝试将my_object
转换为整数。这种方法并不总是可行的,但在编码时是一个好的“第一推荐”。 - robertlaytonreturn float(str_value)
。 - InfiniteStack