Find the number of characters in a file using Python

后端 未结 16 1483
春和景丽
春和景丽 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:16

    Simply skip unwanted characters while calling len,

    import os
    characters=characters+ len([c for c in line if c not in (os.linesep, ' ')])
    

    or sum the count,

    characters=characters+ sum(1 for c in line if c not in (os.linesep, ' '))
    

    or build a str from the wordlist and take len,

    characters=characters+ len(''.join(wordlist))
    

    or sum the characters in the wordlist. I think this is the fastest.

    characters=characters+ sum(1 for word in wordlist for char in word)
    

提交回复
热议问题