Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #79171

Re: Creating a counter

References <loom.20141015T203348-999@post.gmane.org>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-10-15 13:17 -0600
Subject Re: Creating a counter
Newsgroups comp.lang.python
Message-ID <mailman.14890.1413400675.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Oct 15, 2014 at 12:39 PM, Shiva
<shivaji_tn@yahoo.com.dmarc.invalid> wrote:
> Hi,
>
> I am trying to search a string through files in a directory - however while
> Python script works on it and writes a log - I want to present the user with
> count of number of strings found. So it should increment for each string found.
>
> How do I implement it?
>
> If I use a print() within a if condition statement - and execute the script
> in terminal - for each find, the print() prints in new line instead of a
> constantly incrementing counter.

Before the loop, initialize the counter to 0:

    counter = 0

Inside the loop, increment the counter:

    counter = counter + 1  # can be shortened to: counter += 1

Alternatively, if you have all the strings you want to count in a
list, you can just check the length of the list:

    print(len(os.listdir("/some/directory")))

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Creating a counter Ian Kelly <ian.g.kelly@gmail.com> - 2014-10-15 13:17 -0600

csiph-web