zemnl zemnl - 2 years ago 190
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download