Ahmed Ahmed - 2 months ago 5
Python Question

Replace the first 3 white space coming with a character and ignore other white spaces in a text line with python

I have this line text:

09-15-16 05:23:44 A:VCOM 09064 Port 4 Device 10400 Remote 1 10401 Link Up RP2009


the output should be like this:

09-15-16|05:23:44|A:VCOM|09064|Port 4 Device 10400 Remote 1 10401 Link Up RP2009


It should just replace the first 4 white spaces with | and ignore the rest.

This is the simple code I used :

import re
text = "09-15-16 05:23:44 A:VCOM 09064 Port 4 Device 10400 Remote 1 10401 Link Up RP2009"
i = 0
while i< 3:
text = re.sub(' ', '|', text)
text = re.sub(' ', '|', text)
i +=1

print text


I got this output :

09-15-16|05:23:44|A:VCOM|||||09064|Port|4|Device|10400|Remote|1|10401|Link|Up|RP2009

Answer

Maybe try something like this:

text = "09-15-16 05:23:44 A:VCOM     09064 Port 4 Device 10400 Remote 1 10401 Link Up RP2009"
text = text.replace(" ", "|", 3)
text = text.replace("    ", "")
text = text.replace(" ", "|", 1)