zemnl zemnl - 5 months ago 14x
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
for the string but I'm wondering if there is a way to do it using a regex, maybe with the


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.