AppDividend
Latest Code Tutorials

How to Convert Python String to Array

0

Python does not have an inbuilt Array data type; instead, you can convert Python String to List. 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).

Leave A Reply

Your email address will not be published.

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