convert user input to Decimal objects using eval()?

Raymond Hettinger vze4rx4y at verizon.net
Wed Mar 30 03:36:10 EST 2005


> > [Julian Hernandez Gomez]
> >> is there a "easy way" to make eval() convert all floating
> >> numbers to Decimal objects and return a Decimal?

[Raymond Hettinger]
> > from decimal import Decimal
> > import re
> >
> > number =
> > re.compile(r"((\b|(?=\W))(\d+(\.\d*)?|\.\d+)([eE][+-]?\d{1,3})?)")
> > deciexpr = lambda s: number.sub(r"Decimal('\1')", s)

[Terry Reedy]
> This is less obvious and more useful, to me, than some of the recipies in
> the new Cookbook.

Okay, we can fix that.  I've cleaned it up a bit and posted it on ASPN with
references, docs, and a doctest:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393265


Raymond





More information about the Python-list mailing list