我已经编写了一个代码,该代码接收文件并逐行读取,但是当它打印时,它会在每行之间添加换行符。这是我的代码:
in_file = open("in.txt", "r")
line_number = 0
for line in in_file:
print "Line "+ str(line_number) + " " + "("+ str(len(line)) + " " + "chars): "+ str(line)
line_number += 1
打印出来:
Line 0 (13 chars): I am a file.
Line 1 (16 chars): This is a line.
Line 2 (22 chars): This is the last line.
我怎样才能摆脱休息?谢谢!
答案 0 :(得分:1)
使用.replace('\n', '')
print "Line "+ str(line_number) + " " + "("+ str(len(line)) + " " + "chars): "+ str(line).replace('\n', '')
答案 1 :(得分:0)
从您的行中删除新行char或不在print语句中打印新行。在此示例中,我不打印新行:
in_file = open("in.txt", "r")
for num, line in enumerate(in_file, 1):
print "Line", num, "(", len(line), "chars):", line,