Jacob Marshall
Jacob Marshall

Reputation: 192

File IO: len() function not working properly in python

I'm trying to do File IO, and I wrote a program to:

  1. Read the following lines
  2. Print what line number each line is on
  3. Print the total characters in a line
  4. Print the line.

The text I'm trying to read is stored in a file called input.txt. Here is the exact text...

I am a file.
This is a line.
This is the last line.

and here is my function to read that file and print out my desired results.

in1 = open("input.txt", 'r')
x=0
for line in in1:
    print ('Line %d ' % (x)),
    print ("(%d chars): " % (len(line))),
    print (line),

    x += 1

My terminal output should be

Line 0 (12 chars): I am a file.
Line 1 (15 chars): This is a line.
Line 2 (22 chars): This is the last line.

But my actual terminal output is

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.

When my function is counting the length of the line, I believe it is counting the Enter Key I press in order to move to the next line as an extra character. How do I fix this?

Upvotes: 0

Views: 347

Answers (1)

zondo
zondo

Reputation: 20336

That's because each line has a new-line character at the end that you don't see. Use len(line.rstrip()) instead.

Upvotes: 5

Related Questions