Skip to main content
convert-python-string-to-array

How To Convert Python String To Array

This tutorial help to create python string to array. Python does not have an inbuilt array data type, it has a list data type that can be used as an array type. So basically, we are converting a string into a python list.

Python String to Array

We’ll convert String to array in Python. The python string package has split() method. The String.split() method splits the String from the delimiter and returns it as a list item. The split() method default separator is the whitespace but you can specify the separator.

Checkout other python string tutorials:

Syntax

string.split(separator, maxsplit)

Where is parameters are :

  • separator(optional) : It used to split the String.
  • maxsplit(optional) : It specifies the number of splits to do. The default value is -1, which is “all occurrences”.

Example:

#test.py
str = "My name is dominic toretto"
arr = str.split()
print(arr)

Output
['My', 'name', 'is', 'dominic', 'toretto']

We have split string using white space delimiter. The splits() methods used to break the String based on that separator and return the list.

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

Example:

#test.py
str = "My,name,is,dominic,toretto"
arr = str.split()
print(arr)

Output
['My', 'name', 'is', 'dominic', 'toretto']

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.

#test.py
str = "abc"
arr = list(str)
print(arr)

Output:
['a', 'b', 'c']

How to convert a string with comma-delimited items to a list in Python?

We can also convert a string into a comma-separated list, as like in other languages, we have an exploding method that ll break string using delimiter and convert into array.

The split() method help to convert into array.

#test.py
email= "tom, jerry, jim"
email.split(',')

OUTPUT

["tom", "jerry", "tim"]

Leave a Reply

Your email address will not be published. Required fields are marked *