2016-02-26 30 views
1

我已经编写了一个代码,它接收一个文件并逐行读取它,但是当它打印出来时,它会在每一行之间添加一个换行符。这里是我的代码:逐行读取文件时删除换行符

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

使用line.strip() – dnit13

+0

的可能的复制(http://stackoverflow.com /问题/ 275018 /如何-可以-I-删除-格格-A-换行符中的Python) – dnit13

回答

1

使用.replace('\n', '')

print "Line "+ str(line_number) + " " + "("+ str(len(line)) + " " + "chars): "+ str(line).replace('\n', '') 
0

从行中删除新行字符或不打印在打印语句的新线替换从行尾换行符。在这个例子中,我不是打印新行:[?我怎样才能删除(格格)Python中的换行]

in_file = open("in.txt", "r") 
for num, line in enumerate(in_file, 1): 
    print "Line", num, "(", len(line), "chars):", line,