user2198320
user2198320

Reputation: 71

Python len() function adding 1 more

I have tried googling this with no success, but I am trying to read in a file and find the length of each string. Each string is a set of numbers (i.e. 012345). I use the len() function and it works but it is adding 1 more to every line except the last line. I am assuming it is counting the eol/return character. How do I fix this? Thanks

Upvotes: 1

Views: 3967

Answers (3)

Nabeelah Ali
Nabeelah Ali

Reputation: 539

You could trim the whitespace off each line that you read. You can use the strip (strips extra whitespace off both left and right sides), or rstrip function (strips off whitespace from the right hand side) for this.

"My file line.\n".rstrip()

The rstrip() function can also take in arguments, if you want to strip, say, only newline characters.

"My file line.\n".rstrip('\n')

Upvotes: 3

JR Smith
JR Smith

Reputation: 1216

Have you tried using Python's string replace function? It would go something like this:

len(yourString.replace('\n', ''));

Upvotes: 0

Lev Levitsky
Lev Levitsky

Reputation: 65791

You can strip the whitespace:

len(line.strip())

Example:

$ echo 'One
Two' | python -c 'for line in __import__("sys").stdin: print(len(line))'
4
4
$ echo 'One
Two' | python -c 'for line in __import__("sys").stdin: print(len(line.strip()))'
3
3

str.strip docs

Upvotes: 7

Related Questions