3

I am trying to read a source file (for example one in Python) and have each occurrence of a specific character to be replaced with 2 spaces and, also, count all such replaces.

From here, I use this

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(specificChar, '  '), end='')

which works exactly as I want (even though it re-writes every single line).

But, I cannot find a way of counting the total number replaces; I though that trying

counter = 0
if is specificChar in line:
    counter += 1

would not be efficient since I will then be traversing the line once for the counter and once for the line.replace which seems not Pythonic to me.

Is there any other implementation I can consider?

Community
  • 1
  • 1

2 Answers2

2

Use re.subn which replaces and counts, returning a tuple (new_string, number_of_subs_made), like this...

import re
count = 0
for line in file:
    (result, qty) = re.subn(specific_char, '  ', line)
    count += qty
    print(result, end='')

This is similar to Moses's excellent answer but avoids the double-traversal of each line and is still somewhat readable.

Jim Fred
  • 1,076
  • 13
  • 27
1

Use .count to count the number of occurrences of the character in the line before replacing:

count = 0
for line in file:
     count += line.count(specificChar)
     print(line.replace(specificChar, '  '), end='')
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks for the answer. Does this not traverse the line twice as I mentioned in my description? I am concerned whether or not this not an efficient approach. Or perhaps it is not something too inefficient..? –  Jun 02 '16 at 07:41
  • This is more readable and faster than counting with a `for` loop *one-by-one* as in your description – Moses Koledoye Jun 02 '16 at 07:55