[英]Comma after leading zeroes
Desired result (final values in float): 所需结果(浮点数中的最终值):
00 → 0.0 00→0.0
20 → 20.0 20→20.0
15 → 15.0 15→15.0
05 → 0.5 05→0.5
003 → 0.03 003→0.03
01 → 0.1 01→0.1
How would I be supposed to do this? 我应该怎么做呢? The initial values are a string, but when I convert it to float the zeroes disappear.
初始值是一个字符串,但是当我将其转换为浮点型时,零消失了。 Are there any pre-made functions for this?
为此有任何预制功能吗?
This is easily done with regular expressions. 使用正则表达式很容易做到这一点。
In [1]: import re
In [2]: def reformat_numbers(num):
...: return float(re.sub('^0', '0.', num))
...:
In [3]: [reformat_numbers(n) for n in ['00', '20', '15', '05', '003', '01']]
Out[6]: [0.0, 20.0, 15.0, 0.5, 0.03, 0.1]
Another simple implementation taking care of exception as well: 另一个处理异常的简单实现:
import math
x = ['00', '20', '15', '05', '003', '01', '0']
def convert_to_float(val):
try:
if val[0] == '0':
if len(val[1:]) > 0:
decimal_part = float(val[1:])
val = decimal_part / math.pow(10, len(val[1:]))
else:
val = 0.0
else:
val = float(val)
except ValueError:
print('Not a number')
return val
for val in x:
print(convert_to_float(val))
Output: 输出:
0.0
20.0
15.0
0.5
0.03
0.1
0.0
From your examples, it seems like you can just add a decimal after the first char then cast it to float. 从您的示例中,您似乎可以在第一个字符之后添加一个小数,然后将其强制转换为浮点型。 Eg
例如
my_num = '002'
my_num = float(my_num[0] + '.' + my_num[1:])
As always when casting, wrap it in a try/except in case the input is not castable. 与投射时一样,将其包装在try / except中,以防输入不可投射。
I'm not sure what you're trying to do, because you give no specification, only examples. 我不确定您要做什么,因为您没有给出说明,仅给出了示例。 But this works:
但这有效:
for num in ("00", "20", "15", "05", "003", "01"):
if num[0] == '0':
print('0.' + num[1:])
else:
print(num + '.0')
Tested: 测试:
$ python3 convert.py
0.0
20.0
15.0
0.5
0.03
0.1
You can use float. 您可以使用float。
For example: 例如:
a = "20" a =“ 20”
y = float(a) y =浮点数(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.