首页 > 解决方案 > Python:为什么拆分不能正确处理数字

问题描述

如果我想将拆分数字作为我从浮点数转换的字符串,我认为 split() 函数无法正常工作。

主要问题是如何修复我的代码。?

为了向您展示我的问题,我在 python 中编写了简短的脚本。您可以复制并运行。

#!/usr/bin/env python3
# coding=utf-8

def f_test(number):
    print(f"I will split {number}")
    if isinstance(number, float):
        print('This number is float')
        number = str(number)
        print(f'I changed type to str: {type(number)}')
    else:
        print('This number is string')
    l1 = number.split('.')
    print(l1)
    print()


f_test(2.12)
f_test('2.12')

f_test(0.1)
f_test('0.1')

f_test(0.000000001)
f_test('0.000000001')

f_test(0.000107)
f_test('0.000107')

f_test(0.0000107)
f_test('0.0000107')

因为我不知道这个数字的类型,所以我必须检查是浮点数还是字符串。如果是浮点数,我将其转换为 str。

在我看来,将浮点数转换为字符串有问题,因为在转换后 python 将类型显示为字符串,但打印显示以下形式的有效数字 *(base)^exponent for float

对于测试,我使用数字作为浮点数和 str。我得到的你可以在下面看到。

0.000000001 和 0.0000107 的奇怪行为。

通常拆分对于所有数字都不能正常工作,因为浮点数转换为字符串在转换后打印显示像这样的浮点表示的情况 1.07e-5

I will split 2.12
This number is float
I changed type to str: <class 'str'>
['2', '12']

I will split 2.12
This number is string
['2', '12']

I will split 0.1
This number is float
I changed type to str: <class 'str'>
['0', '1']

I will split 0.1
This number is string
['0', '1']

I will split 1e-09
This number is float
I changed type to str: <class 'str'>
['1e-09']

I will split 0.000000001
This number is string
['0', '000000001']

I will split 0.000107
This number is float
I changed type to str: <class 'str'>
['0', '000107']

I will split 0.000107
This number is string
['0', '000107']

I will split 1.07e-05
This number is float
I changed type to str: <class 'str'>
['1', '07e-05']

I will split 0.0000107
This number is string
['0', '0000107']

我正在使用 Python 3.8.6

标签: pythonpython-3.xsplittype-conversion

解决方案


推荐阅读