tags:

views:

84

answers:

3

I've got a python string

s = "Abc(problem=None, fds=5, sff=(2, 1, 0))"
s2 = "Abc(problem=None)"

What I want to do is remove the "problem=None, "

So it'll looks like

s = "Abc(fds=5, sff=(2, 1, 0))"
s2 = "Abc()"

Please mind the ','

How to achieve this? Thanks very much!!

+2  A: 

A regex that will work in both cases is:

/problem=None,?\s*/

The ? makes the comma optional and the \s* will strip any trailing whitespace.

Mark Thomas
A: 
re.sub(r"problem=None,? +", "", s)
John Percival Hackworth
Like the comma, the trailing whitespace is optional, but your regex requires at least one space character to be present. You should use `*` instead of `+`, like the other responders did.
Alan Moore
The OP was asking for removing a string with one space after the comma, making my RE work, albeit with the problem that I'll remove more than they asked for.. In the general case I agree with you though. Thanks for fixing the formatting, I was answering from a device that doesn't play as nice as it could.
John Percival Hackworth
+3  A: 

Removing all syntactically valid whitespace:

>>> import re
>>> re.sub(r"\s*problem\s*=\s*None\s*,?\s*", "", "abc( problem = None , )")
'abc()'
>>> re.sub(r"\s*problem\s*=\s*None\s*,?\s*", "", "abc( problem = None  )")
'abc()'
>>>
John Machin
+1: This is the best, most generic way to handle this.
sdolan