Complex evaluation bug

Paul McGuire ptmcg at austin.rr._bogus_.com
Thu May 18 14:08:57 EDT 2006


"Mel Wilson" <mwilson-to at sympatico.ca> wrote in message
news:Yk2bg.8862$aa4.296336 at news20.bellglobal.com...
> of wrote:
> > a = 1+3j
> > complex(str(a))
> >
> > Why does this not work ? It should
>
> It would be nice.
> Looks like str(1+3j) is returning an expression in string
> form.  Maybe there is no actual complex literal.
>

The problem is that str(1+3j) emits a string enclosed in parens.  Stripping
them off makes the string acceptable to complex's constructor, without
invoking eval.

>>> a = 1+3j
>>> str(a)
'(1+3j)'
>>> complex(str(a))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: complex() arg is a malformed string
>>> complex(str(a)[1:-1])
(1+3j)
>>> complex(str(a).strip("()"))
(1+3j)


-- Paul





More information about the Python-list mailing list