Find the number of characters in a file using Python

后端 未结 16 1706
春和景丽
春和景丽 2021-02-07 00:34

Here is the question:

I have a file with these words:

hey how are you
I am fine and you
Yes I am fine

And it is asked to find the numbe

16条回答
  •  自闭症患者
    2021-02-07 01:18

    You have two problems. One is the line endings and the other is the spaces in between.

    Now there are many people who posted pretty good answers, but I find this method easier to understand:

    characters = characters + len(line.strip()) - line.strip().count(' ')
    

    line.strip() removes the trailing and leading spaces. Then I'm subtracting the number of spaces from the total length.

提交回复
热议问题