search and replace a space with a tab at a specific location in a string
<p>I need some help replacing a space with a tab on a string with multiple spaces.
I need to search the string for a time format such as 08:20:10 and replace the space on the end with a tab.
My code is the following:</p>

<pre><code>alert = '9/14/2016 08:20:10 CH1 This is a test.'
str = re.sub (r'(/d{2}:\d{2}:\d{2})(\s)$', '\t', alert)
</code></pre>

<p>I've been unsuccessful in this endeavor. The output should look like:</p>

<pre><code>9/14/2016 08:20:10    CH1 This is a test.
</code></pre>

<p>What am I doing wrong?</p>

<p>First, don't name your variable <code>str</code>, as this masks the built-in function of that name.</p>

<p>Second, I don't see the need for regex here. Simply <code>split</code> the string and then rejoin it however you like.</p>

<pre><code>&gt;&gt;&gt; alert = '9/14/2016 08:20:10 CH1 This is a test.'
&gt;&gt;&gt; l = alert.split()
&gt;&gt;&gt; new_alert = ' '.join(l[:2]) + '\t' + ' '.join(l[2:])
&gt;&gt;&gt; new_alert
'9/14/2016 08:20:10\tCH1 This is a test.'
</code></pre>

<p>You can also repair your original expression by referring to the captured group in the replacement substring (and fixing the <code>/</code> to a <code>\</code>):</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; re.sub (r'(\d{2}:\d{2}:\d{2})(\s)', r'\1\t', alert)
'9/14/2016 08:20:10\tCH1 This is a test.'
</code></pre>

python