Totoc1001 Totoc1001 - 1 year ago 88
Python Question

How to remove several spaces at the beginning of the line only

I've got a file that look like this:

TOTO TATA
TUTU TITI PAPA
AAA BBB CCCC


And I'd like to be able to substitute only the spaces starting a line with something else.

eg:

eeeTOTO TATA
TUTU TITI PAPA
eeeeeeeeeAAA BBB CCCC


It looks simple, but it does not work for me.

this is what I tried wrongly:

#!/usr/bin/python

#open the file
fs = open("./Tst.tst", 'r')
fd = open("./Out.tst", 'w')

print fs.read()
print fd.read()

for line in fs:
fd.write(line)
for char in line:
if (" ") in char:
char = char.replace(" ", "e" )
fd.write(char)
else:
print char

fd.close()
fs.close()

Answer Source

You can use re.sub with a callback:

In [979]: import re

In [980]: for x in lines.splitlines():
     ...:     print(re.sub('^ +', lambda k: 'e' * len(k.group(0)), x))
     ...:     
eeeTOTO   TATA   
TUTU   TITI  PAPA
eeeeeeeeeAAA BBB   CCCC

As a complete example, consider:

def foo(k):
    'e' * len(k.group(0))

with open("./In.txt", 'r') as fs, open("./Out.txt", 'w') as fd:
    lines = fs.read()
    for x in lines.splitlines():
        print(re.sub('^ +', foo, file=fd)

When a match is encountered, the match object is passed to the callback, which returns another string as the replacement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download