python - 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
解决方案
推荐阅读
- azure-devops-rest-api - 如何通过 Azure 中的 REST API 获取链接到构建管道的工作项列表
- flutter - Flutter中如何使用谷歌云功能?
- javascript - 在另一个文件上显示来自表单的文本输入
- javascript - 删除选定文件路径时未触发 HTML 文件输入事件侦听器
- javascript - 在 Vaadin UI 上 TextArea 自动滚动到底部
- python - 无法使用 psycopg2 从 google colab 连接到 postgres 服务器
- python - 尝试转换基数时如何创建无限循环
- android - 实施 FirebaseMessagingService 时不产生 Firebase 令牌
- android - Android 应用应直接从任何 Activity 关闭
- python - 具有不同假期日期的合并/Concat 2 数据框