How to Convert String to Array in Python

To convert a string to an array in Python, you can use the string.split() method. It splits a string into a list, where each list element is each word that makes up the string.

Syntax

string.split(separator, maxsplit)

Parameters

  1. separator: It takes a separator as an optional parameter to split the String. By default, whitespace is a separator.
  2. maxsplit: It specifies how many splits to do. The default value is -1, which is “all occurrences“.

Return value

It returns a list of strings after breaking the given string by the specified separator.

Visual Representation

Figure 1: Convert String to Array in Python
Figure 1: Converting String to Array in Python

Example 1: Converting a string to an array

string = "I love Python"

arr = string.split()

print(arr)

Output

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

Example 2: Use the split() method with a Separator

Use the split() method with a Separator
Figure 2: Using the split() method with a separator
string = "I,love,Python"

arr = string.split(',')

print(arr)

Output

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

Example 3: Converting a string to an array of characters

You can convert a string to an array of characters using the built-in list() function. When converting a string to an array of characters, whitespaces are also treated as characters.

Converting a string to an array of characters
Figure 3: Converting a string to an array of characters
string = "Python"

arr = list(string)

print(arr)

Output

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

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.