gpt4 book ai didi

python - 将字符串转换为 int()

转载 作者:行者123 更新时间:2023-11-28 19:45:48 26 4
gpt4 key购买 nike

我有一个看起来像这样的数据集:

0 _ _ 23.0186E-03  
10 _ _51.283E-03
20 _ _125.573E-03

其中数字逐行排列(下划线代表空格)。

右侧列中的数字当前是该行字符串的一部分。我正在尝试将右侧的数字转换为数值(0.0230186 等)。一旦它们是简单的数字形式,我就可以用 int() 转换它们,但我需要更改“E”才能到达那里。如果您知道如何针对任何 E 值(例如 E-01、E-22)更改它,那将非常有帮助。

目前我的代码是这样的:

fin = open( 'stringtest1.txt', "r" )  
fout = open("stringtest2.txt", "w")

while 1:
x=fin.readline()

a=x[5:-1]
##conversion code should go here

if not x:
break

fin.close()
fout.close()

最佳答案

我会建议以下转换:

float(x.split()[-1])

str.split()当没有提供参数时,将在空白处拆分,并且 float()会将字符串转换成数字,例如:

>>> '20  125.573E-03'.split()
['20', '125.573E-03']
>>> float('20 125.573E-03'.split()[-1])
0.12557299999999999

关于python - 将字符串转换为 int(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6364444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com