[Solved] How to create a counter for each new instance of string in python?


File input.txt

##### 
pears 
oranges 
##### 
apples 
grapes 
##### 
grapes 
oranges 
#####
apples 
pears
oranges
grapes

File run.py

lines = [l.strip() for l in open('input.txt', 'r').readlines()]
hash_count = 0

for line in lines:
    if line == '#####':
        hash_count += 1
        print(line)
    else:
        print(line + '_' + str(hash_count))

Run it:

$ python run.py

Output:

#####
pears_1
oranges_1
#####
apples_2
grapes_2
#####
grapes_3
oranges_3
#####
apples_4
pears_4
oranges_4
grapes_4

Hope it helps.

6

solved How to create a counter for each new instance of string in python?