How to Convert String to Array in Python

Converting a string to an array in Python can be interpreted in different ways, depending on what you mean by “array”.

  • If you mean a list (a kind of array commonly used in Python), you can simply convert each character or element of the string into an element of a list.
  • If you mean an array in the context of numerical processing, such as a NumPy array, use the NumPy library.

Converting string to list

To convert a string into a list of words (splitting by spaces or another delimiter), use the split() method.

Visual Representation

Figure 1: Convert String to Array in Python

Example 1: Convert String to a List of Words

string = "I love Python"

arr = string.split()

print(arr)

Output

['I', 'love', 'Python']

Example 2: Using a separator

Use the split() method with a Separator

string = "I,love,Python"

arr = string.split(',')

print(arr)

Output

['I', 'love', 'Python']

Example 3: Convert String to a List of Characters

To convert a string to a list of its characters, you can use list().

Convert String to a List of Characters

string = "Python"

arr = list(string)

print(arr)

Output

['P', 'y', 't', 'h', 'o', 'n']

Example 4: Using bytearray()

If you need a mutable array of bytes (for instance, for binary data processing), you can use bytearray().

string = "Python"

arr = bytearray(string, 'utf-8')

print(arr)

Output

bytearray(b'Python')

Convert String to NumPy Array

If you are working with numerical libraries like NumPy and want to convert a string to a NumPy array, you can do so as follows:

import numpy as np

my_string = "Python"
my_array = np.array(list(my_string))

print(my_array)

Output

['P' 'y' 't' 'h' 'o' 'n']

The output is the standard way NumPy displays arrays.

NumPy arrays do not use commas to separate elements, unlike Python lists. This is just a difference in the way NumPy and standard Python display arrays and lists, respectively.

Related posts

Python string to dictionary

Python string to int

Python string to json

4 thoughts on “How to Convert String to Array in Python”

  1. You can use list comprehensions to do str -> char[] as well

    str = ‘abc’
    result = [c for c in str]
    result
    type(result)

    // [‘a’,’b’,’c’]
    // list

    Reply
  2. how to convert a list

    1.2175443743582222
    1.2175624154470546
    1.216812476226702
    1.2135922330097086
    1.2135922330097086
    1.2174474363703431

    to

    [1.2175443743582222,
    1.2175624154470546,
    1.216812476226702,
    1.2135922330097086,
    1.2135922330097086,
    1.2174474363703431]

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.