How to Convert Python String to Array

2
51788
How to Convert Python String to Array

Python does not have an inbuilt Array data type; instead, you can convert Python String to List. Therefore, you can assume a Python list as an array in this example.

Python String to Array

To convert String to array in Python, use String.split() method. The String .split() method splits the String from the delimiter and returns the splitter elements as individual list items. Python String split() method splits the string into a list. You can specify the separator; the default separator is any whitespace.

Syntax

string.split(separator, maxsplit)

Parameters

Both parameters are optional.

It takes a separator as an optional parameter that is used to split the String. By default, whitespace is a separator.

The maxsplit parameter specifies how many splits to do. The default value is -1, which is “all occurrences“.

Example

# app.py

str = "Millie Bobby Brown is Enola Holmes"
arr = str.split()
print(arr)

Output

['Millie', 'Bobby', 'Brown', 'is', 'Enola', 'Holmes']

In this example, we have not explicitly provided the separator, so it takes whitespace as a separator and splits the String based on that separator, and returns the list.

To split the String at a specific character, use the Python split() function.

# app.py

str = "Millie,Bobby,Brown,is,Enola,Holmes"
arr = str.split(',')
print(arr)

Output

['Millie', 'Bobby', 'Brown', 'is', 'Enola', 'Holmes']

In this example, we split the String at the ‘,’ separator.

Python String to Array of Characters

Python String is a sequence of characters. We can convert it to the array of characters using the list() inbuilt function. When converting a string to an array of characters, whitespaces are also treated as characters.

# app.py

str = "MillieB11"
arr = list(str)
print(arr)

Output

['M', 'i', 'l', 'l', 'i', 'e', 'B', '1', '1']

In this example, split the String by converting the String to the list (using typecast).

2 Comments

  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

  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]

Leave A Reply

Please enter your comment!
Please enter your name here

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