Complex numbers (e.g. 3 + 4j) are a built-in Python data type commonly used in scientific computing, signal processing, and engineering applications. Converting them to strings is necessary for logging, API responses, file exports, and user interfaces.
This guide covers standard conversion methods, formatting options, and handling edge cases.
Using str() (Standard Conversion)
The simplest method is Python's built-in str() function:
z = 3 + 4j
s = str(z)
print(s) # Output: (3+4j)
print(type(s)) # Output: <class 'str'>Handling Pure Real or Imaginary Numbers
z1 = complex(5, 0)
print(str(z1)) # (5+0j)
z2 = complex(0, 3)
print(str(z2)) # 3j
z3 = 2 - 5j
print(str(z3)) # (2-5j)Removing Parentheses
When exporting to formats that don't expect parentheses (CSV, plain text), access the components directly:
z = 3 + 4j
if z.imag >= 0:
s = f"{z.real}+{z.imag}j"
else:
s = f"{z.real}{z.imag}j" # Negative sign included automatically
print(s) # 3.0+4.0jReusable Formatting Function
def complex_to_string(z, include_parens=True):
"""Convert complex number to string with formatting options."""
if z.imag >= 0:
result = f"{z.real}+{z.imag}j"
else:
result = f"{z.real}{z.imag}j"
if include_parens:
return f"({result})"
return result
z = 3 - 4j
print(complex_to_string(z, include_parens=False)) # 3.0-4.0j
print(complex_to_string(z, include_parens=True)) # (3.0-4.0j)Controlling Decimal Precision
For scientific data, limiting decimal places improves readability:
z = 1/3 + 1/7j
print(str(z))
formatted = f"({z.real:.2f} + {z.imag:.2f}j)"
print(formatted) Python 3.10+ Direct Formatting
Modern Python allows formatting complex numbers directly:
z = 3.14159 + 2.71828j
print(f"{z:.2f}") # (3.14+2.72j)Comprehensive Formatting Function
def format_complex(z, precision=2, style='standard'):
"""
Format complex number with various styles.
Styles:
- 'standard': (a+bj)
- 'math': a + bi
- 'polar': r∠θ
"""
import math
if style == 'standard':
return f"({z.real:.{precision}f}{z.imag:+.{precision}f}j)"
elif style == 'math':
sign = '+' if z.imag >= 0 else '-'
return f"{z.real:.{precision}f} {sign} {abs(z.imag):.{precision}f}i"
elif style == 'polar':
r = abs(z)
theta = math.degrees(math.atan2(z.imag, z.real))
return f"{r:.{precision}f}∠{theta:.{precision}f}°"
else:
raise ValueError(f"Unknown style: {style}")
z = 3 + 4j
print(format_complex(z, style='standard')) # (3.00+4.00j)
print(format_complex(z, style='math')) # 3.00 + 4.00i
print(format_complex(z, style='polar')) # 5.00∠53.13°Working with Lists and Arrays
Converting collections of complex numbers:
numbers = [1+2j, 3-4j, -5+6j]
strings = [str(z) for z in numbers]
print(strings) # ['(1+2j)', '(3-4j)', '(-5+6j)']
formatted = [f"{z.real:.1f}{z.imag:+.1f}j" for z in numbers]
print(formatted) # ['1.0+2.0j', '3.0-4.0j', '-5.0+6.0j']NumPy Arrays
import numpy as np
arr = np.array([1+2j, 3-4j, 5+6j])
print(arr.astype(str))
format_func = np.vectorize(lambda z: f"{z.real:.1f}{z.imag:+.1f}j")
print(format_func(arr))Pandas DataFrame Formatting
For data analysis workflows:
import pandas as pd
df = pd.DataFrame({
'signal': [1+2j, 3-4j, 0.5+0.5j],
'amplitude': [2.236, 5.0, 0.707]
})
df['signal_str'] = df['signal'].apply(
lambda z: f"{z.real:.2f} + {z.imag:.2f}j" if z.imag >= 0
else f"{z.real:.2f} - {abs(z.imag):.2f}j"
)
print(df)Output:
signal amplitude signal_str
0 1.0+2.0j 2.236 1.00 + 2.00j
1 3.0-4.0j 5.000 3.00 - 4.00j
2 0.5+0.5j 0.707 0.50 + 0.50jParsing Strings Back to Complex Numbers
Converting strings back to complex numbers:
s1 = "3+4j"
z1 = complex(s1)
print(z1) # Output: (3+4j)
s2 = "3 + 4j"
z2 = complex(s2.replace(" ", ""))
print(z2) # Output: (3+4j)
def parse_complex(s):
"""Parse various complex number string formats."""
s = s.replace(" ", "").strip("()")
s = s.replace("i", "j")
return complex(s)
print(parse_complex("(3 + 4j)")) # Output: (3+4j)
print(parse_complex("3 + 4i")) # Output: (3+4j)Summary
| Goal | Method | Output Example |
|---|---|---|
| Simple conversion | str(z) |
(3+4j) |
| No parentheses | f"{z.real}+{z.imag}j" |
3.0+4.0j |
| Fixed precision | f"{z:.2f}" (3.10+) |
(3.00+4.00j) |
| Component precision | f"{z.real:.2f}+{z.imag:.2f}j" |
3.00+4.00j |
| Mathematical notation | Custom function | 3.00 + 4.00i |