0

我有一个写在 excel 文件中的输出。我的值是浮点数,在 python 中,浮点数是点(1/3 = 0.33),但在 excel 中浮点数是逗号(0,33)。如何将所有点转换为逗号......................................................?

import math

print("\nThis program calculates the maximum height and speed of a one stage rocket \n")

Isp = float(input("Write Specific Impulse in seconds = "))
min = float(input("Write the initial mass of the rocket ="))
mfuel = float(input("Write tha mass of fuel = "))
mf = float(input("Write the final mass of the rocket = "))
tb = float(input("Write the time that rockets fuel ends = "))

file = open("Ask_2_AET.csv", "w")

file.write("h in meters")
file.write(";")
file.write("V in m/s")
file.write(";")
file.write("t in seconds\n") 

g = 9.81
t = 0.000001
Ve = g * Isp

while t == tb or t < tb:

    mt = min - mfuel * (t/tb)
    y = g * (-t * Isp * (math.log(min/mt) / ((min/mt) - 1)) + t * Isp - 1/2 * t ** 2)
    V = Ve * math.log(min / mt) - g * t

    t = round(t)
    file.write(str(round(y, 2)))
    file.write(";")
    file.write(str(round(V, 2)))
    file.write(";")
    file.write(str(round(t)))
    file.write("\n")
    t += 1

Vb = V

while V > 0:

    V = Vb - g * t
    h = Vb * t - 1 / 2 * g * t ** 2

    if V > 0:

        file.write(str(round(h, 2)))
        file.write(";")
        file.write(str(round(V, 2)))
        file.write(";")
        file.write(str(round(t)))
        file.write("\n")
        t += 1
    else:
        break
4

3 回答 3

1

你可以使用python中的replace()方法strings。就在编写之前,您可以将数字转换为字符串并使用该replace()方法将点替换为逗号:

num = 3.16

num = str(num).replace(".", ",")
于 2020-12-05T12:53:13.680 回答
0

只需使用

variable.replace(".",",") 

如果它们不是字符串,您可能需要先执行 str() 。

于 2020-12-05T12:52:19.897 回答
0

是你正在阅读的 csv 吗?如果是,您应该考虑使用 csv 模块,它可以让您轻松解析文件。然后,您可以使用 .replace() 将所有 str 转换为 float,如下所示:

我的.csv:1,90;1,90;1,90 2,91;2,92;2,93 3,92;3,92;3,93

>>> import csv
>>> with open('my.csv') as f:
...  for line in f.readlines():
...   line.replace(',' , '.')
...
'1.90;1.90;1.90\n'
'2.91;2.92;2.93\n'
'3.92;3.92;3.93\n'
于 2020-12-05T13:12:27.177 回答