2012-02-02 138 views
-1

我想要顯示什麼在line1line3,它們是來自用戶的輸入。所以我將它分配給變量print_out,但不知道如何使它工作,以便當它在文本文件中寫入時,它將被縮進爲\n。我應該把什麼放在字符串中?Python字符串顯示

line1 = raw_input("line 1: ") #input from user and are store in line1 
line2 = raw_input("line 2: ") #input from user and are store in line2 
line3 = raw_input("line 3: ") #input from user and are store in line3 

print_out = #here i want to assign line1-line 3 as string and assign it to variable print_out 

txt.write(print_out) #will write whatever it is typed inside print_out on to a file 

問題是,我該如何分配東西到print_out?我知道如何做到這一點,但這是更多的編碼,所以我想用字符串來做到這一點。另一種方式是:

txt.write(line1) 
txt.write("\n") 
txt.write(line2) 
txt.write("\n") 
txt.write(line3) 
txt.write("\n") 

但我想用一個字符串來顯示這個,所以我不必寫太多。我該怎麼做,所以它顯示像那樣,但使​​用字符串,而不是繼續寫txt.write輸入新行。謝謝。

+0

從你的帖子,我不能清楚地瞭解你所要完成的是什麼。你可以試試編輯你的問題嗎? – 0101amt 2012-02-02 23:41:12

+0

你應該更清楚地表達自己,並使用可用的方式來設置文本的格式,以使其更具可讀性。 – 2012-02-03 22:54:06

回答

0

你可以做這樣的事情:

print_out = txt.write("{0}\n{1}\n{2}\n".format(line1,line2,line3)) 
+0

「file.write」的返回值是一個字符串,還是你期望'print_out'是什麼? – 2012-02-03 22:53:31

+0

我想通了,但謝謝:) – 2012-02-07 19:45:59

0
print_out = "%s\n" * 3 % (line1, line2, line3) 
txt.write(print_out)