Convert String to Array in Python

It is very usual to work on strings when you are a Python developer.

When I was working on a game development project, I wanted to convert the game leaves, which were in the form of strings, into an array in Python.

In this article, I will explain some important methods to convert string to array in Python. Real-world examples and common issues and solutions when converting strings to lists in Python.

String and Array in Python

A string is a sequence of characters, like letters, numbers, or symbols stored inside quotes.

Example:

text = "Hello"

An array in Python is usually a list, a collection of items stored inside square brackets [], separated by commas.

Example:

fruits = ["apple", "banana", "grape"]

Read How to Convert a List to an Array in Python?

Convert String to Array in Python

Now I will explain various methods to convert string to array in Python.

1. Use the list() Function

The list() function is one of the simplest ways to convert a string to a list in Python. When you apply the list() function to a string, it creates a new list where each character of the string becomes a separate element in the list.

# Our original string
my_string = "Hello"

# Converting the string to a list using list() function
my_list = list(my_string)

# Print the result
print(my_list)

Output:

['H', 'e', 'l', 'l', 'o']

I executed the above example code and added the screenshot below.

String to Array in Python

In this example, the string “Hello” is converted into a list where each character (‘H’, ‘e’, ‘l’, ‘l’, ‘o’) becomes an individual element in the resulting list.

Check out How to Convert a Dictionary to an Array in Python?

2. Use the split() Method

The split() method breaks a string into pieces and puts those pieces into a list. Unlike list() which creates a list of individual characters, split() breaks the string at specified separators.

# Our original string
my_string = "apple,banana,orange,grape"

# Converting the string to a list using split() method
my_list = my_string.split(",")

# Print the result
print(my_list)

Output:

['apple', 'banana', 'orange', 'grape']

I executed the above example code and added the screenshot below.

Python Convert String to Array

The split(",") method looks for commas in the string and uses them as dividing points. It creates a list where each element is the text between the commas.

Read How to Check if an Array is Empty in Python?

3. Use List Comprehension

List comprehension provides a concise way to create lists in Python. It’s an efficient technique that can be used to transform a string into a list with more flexibility.

# Our original string
my_string = "Hello123"

# Converting the string to a list using list comprehension
# Only including alphabetic characters
my_list = [char for char in my_string if char.isalpha()]

# Print the result
print(my_list)

Output:

['H', 'e', 'l', 'l', 'o']

I executed the above example code and added the screenshot below.

How to Convert String to Array in Python

4. Use array Module

The array module in Python creates compact, efficient arrays of basic data types. Unlike lists which can hold mixed data types, arrays from this module can only store items of a single type.

import array

# Our original string
my_string = "Hello"

# Converting string to an array of characters using array module
# 'u' type code represents Unicode character
my_array = array.array('u', my_string)

# Print the result
print(my_array)
print(my_array.tolist())  # Convert to list to see it better

Output:

array('u', 'Hello')
['H', 'e', 'l', 'l', 'o']

5. Use NumPy

NumPy is a powerful library for numerical computing in Python. It provides a high-performance array object called ndarray that can be more efficient than Python’s built-in lists, especially for large datasets and numerical operations.

import numpy as np

# Our original string
my_string = "1,2,3,4,5"

# Converting string to NumPy array
my_array = np.fromstring(my_string, dtype=int, sep=',')

# Print the result
print(my_array)
print(type(my_array))

Output:

[1 2 3 4 5]
<class 'numpy.ndarray'>

Check out How to Check the Length of an Array in Python?

Real-World Example: Analyze Customer Purchase Data

Let us consider a practical, real-world example where converting a string to a list is useful. Imagine you’re analyzing customer data received as a CSV (Comma-Separated Values) string.

# Raw data received as a string (like from a file or API)
customer_data = """
John,34,New York,Laptop,1200
Sarah,28,Los Angeles,Smartphone,800
Mike,42,Chicago,Headphones,150
Emma,31,Boston,Tablet,350
"""

# Process the data
customers = []
for line in customer_data.strip().split('\n'):
    if line:  # Skip empty lines
        # Convert each line to a list
        customer = line.split(',')
        
        # Extract and convert data types as needed
        name = customer[0]
        age = int(customer[1])
        city = customer[2]
        product = customer[3]
        price = float(customer[4])
        
        # Create a dictionary for each customer
        customer_dict = {
            'name': name,
            'age': age,
            'city': city,
            'product': product,
            'price': price
        }
        
        customers.append(customer_dict)

# Now we can perform analysis
total_sales = sum(customer['price'] for customer in customers)
average_age = sum(customer['age'] for customer in customers) / len(customers)

print(f"Processed {len(customers)} customer records")
print(f"Total sales: ${total_sales}")
print(f"Average customer age: {average_age:.1f} years")

# Filter data
new_york_customers = [c for c in customers if c['city'] == 'New York']
print(f"Customers from New York: {len(new_york_customers)}")

Output:

Processed 4 customer records
Total sales: $2500.0
Average customer age: 33.8 years
Customers from New York: 1

This example demonstrates how string-to-list conversion is a fundamental step in real-world data processing. It’s often the first step in a data pipeline when working with text data from various sources

Read How to Initialize an Array in Python?

Common Issues and Solutions When Converting Strings to Lists in Python

Let me explain to you some common issues that you might face while converting strings to lists in Python and also I explain solutions to them.

1. Empty Strings Producing Empty Arrays

  • Issue: Converting an empty string with list() or split() may return an empty list.
  • Solution: Check for an empty string before conversion.

2. Converting to Wrong Data Types

  • Issue: Trying to convert numeric characters into integers directly can cause errors if not handled properly.
  • Solution: Use list comprehension to cast string digits to integers.

3. Encoding Errors When Converting to Byte Arrays

  • Issue: Encoding a string to a byte array might throw errors if encoding is not specified or unsupported characters exist.
  • Solution: Always specify encoding (like 'utf-8') explicitly.

4. Misunderstanding Between List and Array Modules

  • Issue: Confusion between Python’s built-in list() and the array module when creating arrays.
  • Solution: Use list() for general-purpose arrays and array module for type-specific arrays.

6. Incorrect Use of Split Delimiter

  • Issue: Using the wrong delimiter in split() might not produce the expected result.
  • Solution: Make sure you know what character separates your string items.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.