zemnl zemnl - 7 months ago 29
Python Question

Python replace regex

I have a string in which there are some attributes that may be empty:

[attribute1=value1, attribute2=, attribute3=value3, attribute4=]


With python I need to sobstitute the empty values with the value 'None'. I know I can use the
string.replace('=,','=None,').replace('=]','=None]')
for the string but I'm wondering if there is a way to do it using a regex, maybe with the
?P<name>
option.

Answer

You can use

import re

s = '[attribute1=value1, attribute2=, attribute3=value3, attribute4=]'
re.sub(r'=(,|])', r'=None\1', s)

\1 is the match in parenthesis.