Search code examples
pythonregexdata-cleaning

Regex in Python (30 M)


I have the following text :

Adam, 30 M, Husband

Expected Output :

Adam, 30, M, Husband,

My Approach :

re.sub(r'\b(\d{1,2}\s\w{1},)\b', r'\1,', text)

How can I get a comma between 30 and M as shown in the output above?


Solution

  • Try this:

    >>> s = 'Adam, 30 M, Husband'
    >>> re.sub(r'(?is)(\d+)(\s)', '\\1, ', s)
    'Adam, 30, M, Husband'