Skip to main content

How to Convert Complex Numbers to Strings in Python

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'>
note

Python uses j for the imaginary unit, following electrical engineering conventions rather than the mathematical i. The parentheses are added automatically to distinguish complex numbers from surrounding text.

Handling Pure Real or Imaginary Numbers

# Pure real (imaginary part is 0)
z1 = complex(5, 0)
print(str(z1)) # (5+0j)

# Pure imaginary (real part is 0)
z2 = complex(0, 3)
print(str(z2)) # 3j

# Negative imaginary
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

# Handle positive and negative imaginary parts
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.0j

Reusable 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

# Default str() shows full precision
print(str(z))
# Output: (0.3333333333333333-0.14285714285714285j)

# Format to 2 decimal places
formatted = f"({z.real:.2f} + {z.imag:.2f}j)"
print(formatted)
# Output: (0.33 + 0.14j)

Python 3.10+ Direct Formatting

Modern Python allows formatting complex numbers directly:

# Python 3.10+
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:

# List of complex numbers
numbers = [1+2j, 3-4j, -5+6j]

# Convert all to strings
strings = [str(z) for z in numbers]
print(strings) # ['(1+2j)', '(3-4j)', '(-5+6j)']

# Custom formatting for all
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])

# Default string conversion
print(arr.astype(str))
# ['(1+2j)' '(3-4j)' '(5+6j)']

# Custom formatting with vectorize
format_func = np.vectorize(lambda z: f"{z.real:.1f}{z.imag:+.1f}j")
print(format_func(arr))
# ['1.0+2.0j' '3.0-4.0j' '5.0+6.0j']

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]
})

# Format complex column
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.50j

Parsing Strings Back to Complex Numbers

Converting strings back to complex numbers:

# Standard format works directly
s1 = "3+4j"
z1 = complex(s1)
print(z1) # Output: (3+4j)

# With spaces (needs cleaning)
s2 = "3 + 4j"
z2 = complex(s2.replace(" ", ""))
print(z2) # Output: (3+4j)

# Robust parsing function
def parse_complex(s):
"""Parse various complex number string formats."""
# Remove spaces and parentheses
s = s.replace(" ", "").strip("()")

# Handle 'i' notation
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

GoalMethodOutput Example
Simple conversionstr(z)(3+4j)
No parenthesesf"{z.real}+{z.imag}j"3.0+4.0j
Fixed precisionf"{z:.2f}" (3.10+)(3.00+4.00j)
Component precisionf"{z.real:.2f}+{z.imag:.2f}j"3.00+4.00j
Mathematical notationCustom function3.00 + 4.00i
Best Practice

In Python 3.10+, use f"{z:.2f}" to format complex numbers directly with precision control. For older versions or custom layouts, access .real and .imag separately. Always handle the sign of the imaginary part explicitly when building custom formats.