nedla2004 nedla2004 - 1 year ago 65
Python Question

Regex Change Space Separated Items To Comma Separated Items

I have this regex to change a list that is separated by spaces to a list separated by commas,

re.sub(r'(\w+)', r'\1,', text)
, but I need it to only match if the line starts with
, like this:

xyz a bcd ef --> xyz a,bcd,ef

But should not change any thing for a line that does not start with
, like this:

xy abc def #Nothing changes

xyz .*(\w+)
does not work, because it only matches the
xyz a bcd
and does not separate the
and the

Answer Source

What about something like this:

if re.match(r'xyz', text):
    line = text.partition('xyz ')
    text = line[1] + line[2].replace(' ', ',')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download