在Python中如何将点交换为逗号?

2024-06-08 19:49:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个写在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

Tags: oftheininputfloatmintbfile
3条回答

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

num = 3.16

num = str(num).replace(".", ",")

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

my.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'

只用

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

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

相关问题 更多 >