Replace the first 3 white space coming with a character and ignore other white spaces in a text line with python
<p>I have this line text: </p>

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

<p>the output should be like this:</p>

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

<p>It should just replace the first 4 white spaces with | and ignore the rest.</p>

<p>This is the simple code I used :</p>

<pre><code>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&lt; 3:
    text = re.sub(' ', '|', text)
    text = re.sub('     ', '|', text)
    i +=1

print text
</code></pre>

<p>I got this output :</p>

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

<p>You don't need regex for that. Just use <code>str.split</code> with a <code>maxsplit</code>:</p>

<pre><code>&gt;&gt;&gt; s = '09-15-16 05:23:44 A:VCOM     09064 Port 4 Device 10400 Remote 1 10401 Link Up RP2009'
&gt;&gt;&gt; *first, last = s.split(maxsplit=4)
&gt;&gt;&gt; '|'.join(first) + '|' + last
'09-15-16|05:23:44|A:VCOM|09064|Port 4 Device 10400 Remote 1 10401 Link Up RP2009'
</code></pre>

<p>For Python 2:</p>

<pre><code>&gt;&gt;&gt; s = '09-15-16 05:23:44 A:VCOM     09064 Port 4 Device 10400 Remote 1 10401 Link Up RP2009'
&gt;&gt;&gt; items = s.split(None, 4)
&gt;&gt;&gt; '|'.join(items[:-1]) + '|' + items[-1]
'09-15-16|05:23:44|A:VCOM|09064|Port 4 Device 10400 Remote 1 10401 Link Up RP2009'
</code></pre>

python regex