2017-04-07 25 views
-1

我想寫一個文件中的兩個變量。我的意思是,這是我的代碼:如何在一行中寫入兩個變量?

file.write("a = %g\n" %(params[0])) 
file.write("b = %g\n" %(params[1])) 

,我想在我的文件寫的是:

f(x) = ax + b 

其中aparams[0]bparams[1],但我不知道如何做到這一點?

謝謝你的幫助!

+0

你應該看看是否 – LB40

回答

0

如果所有你想寫信給你的文件是f(x) = ax + b其中abparams[0]params[1],分別,只是這樣做:

file.write('f(x) = %gx + %g\n' % (params[0], params[1])) 

'f(x) = %gx + %g' % (params[0], params[1])簡直是字符串格式化,在那裏你把ab在他們的正確空間。

編輯:如果你正在使用Python 3.6,你可以使用F-字符串:

a, b = params[0], params[1] 
file.write(f'f(x) = {a}x + {b}\n') 
+0

'file.write()中的'format'字符串方法'自動添加一個新隊? – Barmar

+0

從閱讀[docs](https://docs.python.org/3/library/io.html#io.TextIOWrapper),我沒有看到任何指示自動寫入換行符的內容。所以你必須在字符串的末尾加上'\ n'字符。 – blacksite

+0

這就是我的觀點 - 你忘了換行符。 – Barmar

0
"f(x) = {a}x + {b}".format(a=params[0], b=params[1]) 

是一個乾淨的解決方案

0

對不起,我不知道Python,但我猜這

f = open('file', 'w') 
x = 0; 
a = 0; 
b = 0; 
result = a*x+b 
a = str(a) 
b = str(b) 
x = str(x) 
result = str(result) 
f.write("f("+x+")="+result) #this is if you want result to be shown 
print("f("+x+")="+result) 

#or 

f.write("f("+x+")="+a+""+x+"+"+b) #this is if you want actually show f(x)= ax+b 
print("f("+x+")="+a+""+x+"+"+b) 

再次我不知道Python的,但是這是我想出用:https://repl.it/HARP/1

我希望這有助於

0

你的目標是實現的是寫下面的公式寫在文件裏面。

f(x) = ax + b where a is params[0] and b is params[1]

你應該做的是

file.write('f(x) = %gx + %g' % (param[0], param[1])) 

將寫

"f(x) = 2x + 3" # if params[0] and params[1] are 2 and 3 resp 

你在做什麼是

file.write("a = %g\n" %(params[0])) 
file.write("b = %g\n" %(params[1])) 

這將在寫文件爲:

a = 2 
b = 3 

如果PARAMS [0],而params [1]是2和3分別

相關問題