with open ("source.txt","r") as file:
line=file.readlines()
a=line[0].strip()
a=int(a)
b=line[1].strip()
b=int(b)
def gcd(c,d):
if d==0:
return c
else:
return gcd(d,c%d)
e=gcd(a,b)
gcd=("GCD of", a,"and", b,"is",e)
Lcm=("LCM of", a,"and", b,"is",a*b//e)
with open ("Finaldes1.txt","w") as Finaldes:
line1="{0}\n{1}".format(gcd,Lcm)
linaldes.write(line1)
但是当我打开最终文件时,数据写在这样的引号内('GCD of',4,'和',6,'是',2)('LCM of',4,'和',6, '是',12)。我最后和中间不需要这个引号。怎么办?
那是因为你将元组保存到你的文件中。您可以将它们转换为如下字符串:
gcd_string = " ".join(str(x) for x in gcd)
然后像这样保存:
line1="{0}\n{1}".format(gcd_string,Lcm_string)
或者首先,您可以将它们保存为字符串
gcd = "GCD of {0} and {1} is {2}".format(a, b, e)
我认为:
gcd=("GCD of %d and %d is %d" % (a, b, e))
Lcm=("LCM of %d and %d is %d" % (a*b//e))