1

I've written a code that takes in a file and reads it line by line but when it prints it adds a line break in-between each line. Here's my code:

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

It prints this:

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.

How can I get rid of the breaks? Thanks!

relentlessruin
  • 81
  • 1
  • 2
  • 5
  • Possible duplicate of [How can I remove (chomp) a newline in Python?](http://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-newline-in-python) – dnit13 Feb 26 '16 at 07:24

2 Answers2

1

Replace newline from end of line using .replace('\n', '')

print "Line "+ str(line_number) + " " + "("+ str(len(line)) + " " + "chars): "+ str(line).replace('\n', '')
mmuzahid
  • 2,252
  • 23
  • 42
0

Remove the new line char from your line or don't print a new line in your print statement. In this example, I am not printing a new line:

in_file = open("in.txt", "r")
for num, line in enumerate(in_file, 1):
    print "Line", num, "(", len(line), "chars):", line,
helloV
  • 50,176
  • 7
  • 137
  • 145