image

In Python, we do not have an in-built array data type. However, we can convert Python string to list, which can be used as an array type.

Python String to Array

In the earlier tutorial, we learned how to convert list to string in Python. Here we will look at converting string to list with examples.

We will be using the String.split() method to convert string to array in Python.

Python’s split() method splits the string using a specified delimiter and returns it as a list item. The delimiter can be passed as an argument to the split() method. If we don’t give any delimiter, the default will be taken as whitespace.

split() Syntax

The Syntax of split() method is

string.split(separator, maxsplit)

split() Parameters

The split() method takes two parameters, and both are optional.

  • separator – The delimiter that is used to split the string. If not specified, the default would be whitespace.
  • maxsplit – The number of splits to be done on a string. If not specified, it defaults to -1, which is all occurrences.

Example 1: Split the string using the default arguments

In this example, we are not passing any arguments to the split() method. Hence it takes whitespace as a separator and splits the string into a list.

# Split the string using the default arguments

text= "Welcome to Python Tutorials !!!"
print(text.split())

Output

['Welcome', 'to', 'Python', 'Tutorials', '!!!']

Example 2: Split the string using the specific character

In this example, we split the string using a specific character. We will be using a comma as a separator to split the string. 

# Split the string using the separator

text= "Orange,Apple,Grapes,WaterMelon,Kiwi"
print(text.split(','))

Output

['Orange', 'Apple', 'Grapes', 'WaterMelon', 'Kiwi']

Python String to Array of Characters

If you want to convert a string to an array of characters, you can use the list() method, an inbuilt function in Python.

Note: If the string contains whitespace, it will be treated as characters, and whitespace also will be converted to a list.

Example 1: String to array using list() method

# Split the string to array of characters

text1= "ABCDEFGH"
print(list(text1))

text2="A P P L E"
print(list(text2))

Output

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
['A', ' ', 'P', ' ', 'P', ' ', 'L', ' ', 'E']

You can also use list comprehension to split strings into an array of characters, as shown below.

Example 2: String to array using list comprehension

# Split the string to array of characters using list Comprehension

text1= "ABCDEFGH"
output1= [x for x in text1]
print(output1)

text2="A P P L E"
output2=[x for x in text2]
print(list(text2))

Output

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
['A', ' ', 'P', ' ', 'P', ' ', 'L', ' ', 'E']

Total

0

Shares