获取浮点中某些数字的位置(python)

获取浮点中某些数字的位置(python),python,floating-point,Python,Floating Point,假设我有一个浮点0.001000,那么我想作为输出4 更多示例: 0.1 -> 2 1 -> 1 0.00001000 -> 6 所有输入看起来都是这样的(带有1和0) 如何在python3.6中实现这一点 或者有一种方法可以直接将浮点数截断为同一个数字? e、 g 转换为字符串 index = str(my_float).find('1') 诀窍是计算小数点 if index == 0: output = 1 else: output = index 仅

假设我有一个浮点0.001000,那么我想作为输出4

更多示例:

0.1 -> 2
1 -> 1
0.00001000 -> 6
所有输入看起来都是这样的(带有1和0) 如何在python3.6中实现这一点

或者有一种方法可以直接将浮点数截断为同一个数字? e、 g

转换为字符串

index = str(my_float).find('1')
诀窍是计算小数点

if index == 0:
    output = 1
else:
    output = index
仅当小数点前严格有一位数字时,此选项才起作用

或者:

my\u float
的倒数

my_float_inverse = 1/my_float
然后转换为字符串并获取长度

output = len(str(my_float_inverse))

同样,仅当
my_float浮动有时很残酷时才有效。无论如何,如果您的浮点值总是小于或等于1,则可以使用这样的代码段

import math
f = 0.00001 # your float

int(math.log10(round(1/f)))+1
只需执行以下操作:

my_float = 0.001000

# Converts your float to a string without the '.'
my_str = str(my_float).replace('.', '')

# Get the index of the first '1' in the string
index_of_first_one = my_str.index('1') + 1

print(index_of_one)  # 4

这个方法只有在你的
float

中有
1
时才有效。我不清楚为什么
0.1
应该是2,等等。我唯一能想到的是类似于-log10(x)的东西。@WillemVanOnsem,因为我如何检测“1.00”将它们转换成字符串,然后对该字符串进行操作<代码>我的浮点数=0.001;str(我的浮点数)。找到(“1”)
@Coal\听起来不错,我会试试it@J.Daniel. 您是在处理字符串还是浮动对象?浮点对象永远不会显示尾随零,除非它是一个整数(例如
1.0
)。您试图截断值的哪些特定部分?如果第一个值是
10.0
,第二个值是
2.44521
,结果应该是什么?那么
0.1
1
,或者
2
0.001
呢?在这里使用
find()
是一个糟糕的选择,因为如果找不到目标,它会返回
-1
。此外,您的代码将失败,例如
1.001
0.001001
。当
0.001
0.00101
不应该失败时,会给出不同的结果。
my_float_inverse = 1/my_float
my_float = 0.001000

# Converts your float to a string without the '.'
my_str = str(my_float).replace('.', '')

# Get the index of the first '1' in the string
index_of_first_one = my_str.index('1') + 1

print(index_of_one)  # 4