In Python, a complex number is represented as a + bj
, where a
is the real part and b
is the imaginary part. When we have a complex number in string format, such as "3+4j"
, we may need to convert this back into a Python complex number object to perform arithmetic operations. This article demonstrates several methods to achieve this conversion, handling strings such as "3+4j"
with the expected output being a complex number object: 3+4j
.
Method 1: Using the complex() Constructor
The complex()
constructor in Python can be used to turn a string into a complex number. It accepts strings formatted as 'real+imaginaryj'
and returns a complex number object. Note that spaces within the string are not allowed.
Here’s an example:
num_str = "3+4j" num_complex = complex(num_str) print(num_complex)
Output:
(3+4j)
This snippet demonstrates the direct conversion of a string representing a complex number into a complex number object using the built-in complex()
function. The string "3+4j"
is passed to the function, and it returns the complex number object (3+4j)
.
Method 2: Using ast.literal_eval
The ast.literal_eval()
function can safely evaluate a string containing a Python literal or container display. It works well for strings that represent complex numbers and is a good choice when extra caution is needed to prevent code injection.
Here’s an example:
import ast num_str = "3+4j" num_complex = ast.literal_eval(num_str) print(num_complex)
Output:
(3+4j)
This code utilizes the ast.literal_eval()
method to evaluate the string "3+4j"
as a literal expression, producing the complex number object (3+4j)
. Itβs a safe alternative to the built-in eval()
function.
Method 3: Using Regular Expressions (re module)
By using regular expressions, we can parse the real and imaginary parts of a complex number from a string. This technique is useful if the string format can vary and may not be directly suitable for the complex()
constructor.
Here’s an example:
import re num_str = "Real part: 3, Imaginary part: 4j" match = re.search(r'([+-]?\\d+)([+-]?\\d+)?j', num_str) num_complex = complex(match.group(1), match.group(2).rstrip('j')) print(num_complex)
Output:
(3+4j)
This snippet uses the Python re
module to search for patterns in the string that represent the real and imaginary parts, then uses these parts to create a complex number object with the complex()
constructor.
Bonus One-Liner Method 4: Using eval with Safety Check
Warning: The eval()
function should be used with caution, as it can execute arbitrary code. It’s included here for educational purposes and should be avoided or used very carefully.
Here’s an example:
num_str = "3+4j" num_complex = eval(num_str) if '+' in num_str or '-' in num_str else None print(num_complex)
Output:
(3+4j)
This one-liner uses a conditional expression to pass the string to eval()
only if it contains +
or -
, to somewhat limit potential malicious content, though eval()
still poses significant risks.
Summary/Discussion
- Method 1: Using the complex() Constructor. This is the simplest and most straightforward method. It doesnβt require importing any modules. However, it only works if the string is properly formatted.
- Method 2: Using ast.literal_eval. Safe alternative to
eval()
. It works well but can be overkill for simple cases and is slower compared to the directcomplex()
constructor. - Method 3: Using Regular Expressions. Very flexible and can handle various string formats. However, it adds complexity and requires careful handling of regular expression patterns.
- One-Liner Method 4: Using eval with Safety Check. Concise, but potentially very dangerous. It should be used with extreme caution and is not recommended for use in production code.