Find the number of characters in a file using Python

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

    How's this? It uses a regular expression to match all non-whitespace characters and returns the number of matches within a string.

    import re
    
    DATA="""
    hey how are you
    I am fine and you
    Yes I am fine
    """
    
    def get_char_count(s):
        return len(re.findall(r'\S', s))
    
    if __name__ == '__main__':
        print(get_char_count(DATA))
    

    Output

    35
    

    The image below shows this tested on RegExr:

提交回复
热议问题