Converting = to ==
gbreed at cix.compulink.co.uk
gbreed at cix.compulink.co.uk
Fri Apr 28 06:47:12 EDT 2000
On Thu, 27 Apr 2000, Warren Postma wrote:
> I have an "end user query tool" that uses Python expressions, but I want
> comparisons to be able to be written either as A=B or A==B then I want
> to
> compare them using Python's Eval function.
>
> Problem is if you search and replace all = with == then users have to
> use
> the single-equals convention, and some of them will be python
> programmers,
> and will want to use the "non idiot mode" of the query tool.
That's not the only problem. You'll also find != gets converted to !==,
<= to <== and >= to >==. This would not be the expected behaviour in "non
idiot mode".
> So i did this, but is there a better way?
>
> >>> string.replace( string.replace("a=b a==b", "=", "=="),
> > "====","==")
> a==b a==b
If you want to catch != etc as well, you'll need
s = string.replace("a=b a==b b!=c", "=", "==")
s = string.replace(s,"====","==")
s = string.replace(s,"!==","!=")
s = string.replace(s,"<==","<=")
s = string.replace(s,">==",">=")
Or you could use a regular expression. I think this works:
s = re.sub("([^<>!=])=([^=])",r"\1==\2","a=b a==b b!=c")
Or the equivalent:
expr = re.compile("""
([^<>!=]) # check for no preceding <,>,! or =
= # matches = but not ==,<=, >= or !=
([^=]) # catch both parts of ==
""", re.VERBOSE)
s = expr.sub(r"\1==\2","a=b a==b b!=c")
Which is clearer than a one-line regular expression, but longer than doing
all the substitutions. It may be more efficient if the expression is only
compiled once, but executed many times.
More information about the Python-list
mailing list