Creating a counter

Gary Herron gary.herron at islandtraining.com
Wed Oct 15 16:04:03 EDT 2014


On 10/15/2014 11:39 AM, Shiva 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.
>
> Thanks,
> Shiva
>

The question seems confuse the word "increment".

If you are asking how to count, plenty of responders have answered
     count = count+1
and similar.

However, the second paragraphs seems to use the word "increment" to mean 
displaying the counter on a single line overwriting itself instead of a 
scrolling list of values one-per-line.  The solution may depend on what 
is displaying the value as you write it out, but if it's a 
terminal/command-prompt /console-window, then you want the write to 
finish with a carriage-return alone instead of a 
carriage-return/new-line combination.  In Python that is represented 
with a \r instead of a \n.

Python2:
   print counter, '\r', # The ending comma means do NOT output the usual \n

Python3:
   print(counter, end='\r')

Gary Herron




More information about the Python-list mailing list