'complex' function with string argument.

Christian Gollwitzer auriocus at gmx.de
Tue Mar 18 08:04:44 CET 2014

Am 15.03.14 17:26, schrieb Jayanth Koushik:
> This is regarding the inbuilt 'complex' function. The python docs
> say: "Note: When converting from a string, the string must not
> contain whitespace around the central + or - operator. For example,
> complex('1+2j') is fine, but complex('1 + 2j') raises ValueError."

It's funny that you ask this question exactly now; because I'm currently 
implementing a compiler for a small language that understands complex 
numbers. As others have explained, the basic issue is the question how 
to parse an expression like


is it "complex(1+2i) times 3" or is it sum of 1 and product of complex 
2i and 3? The answer that python does it by parsing imaginary literals 
and then combining them back using peephole optimization was helpful, 
thanks for that!


More information about the Python-list mailing list