[英]How to write a program in Python for printing a “string” at the end of a line in the file?
input_file
包含: Hi How are you
預期輸出為: AHi How are youB
嘗試以下程序:
input = open("input_file",'r')
output = open("output_file",'w')
for line in input:
newline = "A" + line + "B"
output.write(newline)
input.close()
output.close()
我得到以下輸出:
AHi How are you
B
請建議如何更改程序?
當您從input
文件中讀取該line
,它實際上看起來像:
"Hi How are you\n"
即在行尾包含換行符。 因此,在添加'A'
和'B'
它看起來像:
"AHi How are you\nB"
# ^ still has newline
您會在輸出中看到換行符。
刪除此錯誤的最小方法是添加str.strip()
以刪除該line
開頭和結尾的所有空格(包括換行符):
newline = "A" + line.strip() + "B"
但我建議也切換到更現代的字符串格式 :
newline = "A{0}B".format(line.strip())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.