Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can we unpack a string of integers to complex numbers in Python?
A string containing two integers separated by a comma can be unpacked and converted into a complex number. Python provides several approaches to achieve this conversion.
Method 1: Using split() and Indexing
First, split the string into a list of string digits, then convert each part to integers for the complex() function ?
s = "1,2".split(",")
print("Split result:", s)
# Convert to complex number
result = complex(int(s[0]), int(s[1]))
print("Complex number:", result)
Split result: ['1', '2'] Complex number: (1+2j)
Method 2: Using Unpacking with map()
Use map() to convert all parts to integers simultaneously, then unpack them ?
s = "3,4"
real, imag = map(int, s.split(","))
result = complex(real, imag)
print("Complex number:", result)
Complex number: (3+4j)
Method 3: One-Line Solution
Combine all operations in a single line using unpacking ?
s = "5,6"
result = complex(*map(int, s.split(",")))
print("Complex number:", result)
Complex number: (5+6j)
Handling Different Formats
You can adapt this approach for different separators or formats ?
# Different separators
s1 = "7 8" # space separator
s2 = "9:10" # colon separator
result1 = complex(*map(int, s1.split(" ")))
result2 = complex(*map(int, s2.split(":")))
print("Space separated:", result1)
print("Colon separated:", result2)
Space separated: (7+8j) Colon separated: (9+10j)
Comparison
| Method | Readability | Best For |
|---|---|---|
| split() + indexing | High | Beginners, clear steps |
| map() + unpacking | Medium | Intermediate users |
| One-line solution | Low | Concise code |
Conclusion
Use split() and complex() to unpack string integers into complex numbers. The map() function with unpacking provides a more elegant solution for this conversion.
Advertisements
