mcristan mcristan - 2 months ago 7
Python Question

search and replace a space with a tab at a specific location in a string

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:

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)


I've been unsuccessful in this endeavor. The output should look like:

9/14/2016 08:20:10 CH1 This is a test.


What am I doing wrong?

Answer

How about a positive lookbehind without a line terminator:

>>> import re
>>>
>>> re.sub(r'(?<=\d{2}:\d{2}:\d{2})\s', '\t', alert)
'9/14/2016 08:20:10\tCH1 This is a test.'
>>>
>>> print(_)
9/14/2016 08:20:10      CH1 This is a test.

Also, your /d should have read \d

Comments