Convert string to array python

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.

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).

split() is your friend here. I will cover a few aspects of split() that are not covered by other answers.

  • If no arguments are passed to split(), it would split the string based on whitespace characters (space, tab, and newline). Leading and trailing whitespace is ignored. Also, consecutive whitespaces are treated as a single delimiter.

Example:

>>> " \t\t\none two three\t\t\tfour\nfive\n\n".split() ['one', 'two', 'three', 'four', 'five']
  • When a single character delimiter is passed, split() behaves quite differently from its default behavior. In this case, leading/trailing delimiters are not ignored, repeating delimiters are not "coalesced" into one either.

Example:

>>> ",,one,two,three,,\n four\tfive".split(',') ['', '', 'one', 'two', 'three', '', '\n four\tfive']

So, if stripping of whitespaces is desired while splitting a string based on a non-whitespace delimiter, use this construct:

words = [item.strip() for item in string.split(',')]
  • When a multi-character string is passed as the delimiter, it is taken as a single delimiter and not as a character class or a set of delimiters.

Example:

>>> "one,two,three,,four".split(',,') ['one,two,three', 'four']

To coalesce multiple delimiters into one, you would need to use re.split(regex, string) approach. See the related posts below.

Related

  • string.split() - Python documentation
  • re.split() - Python documentation
  • Split string based on regex
  • Split string based on a regular expression

In this program, we will try to convert a given string to a list, where spaces or any other special characters, according to the users choice, are encountered. To do this we use the split() method in string.

string.split("delimiter")

Examples:

Input : "Geeks for Geeks" Output : ['Geeks', 'for', 'Geeks']Input : "Geeks-for-Geeks" Output : ['Geeks', 'for', 'Geeks']

Method#1: Using split() method

The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string. If a delimiter is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Example 1A:

Python3

def Convert(string):

    li = list(string.split(" "))

    return li

str1 = "Geeks for Geeks"

print(Convert(str1))

Output

['Geeks', 'for', 'Geeks']

Example 1B: 

Python3

def Convert(string):

    li = list(string.split("-"))

    return li

str1 = "Geeks-for-Geeks"

print(Convert(str1))

Output

['Geeks', 'for', 'Geeks']

Method#2: Using string slicing:

Python3

def Convert(string):

    list1=[]

    list1[:0]=string

    return list1

str1="ABCD"

print(Convert(str1))

Output:

['A','B','C','D']

Method#3: Using re.findall() method 

This task can be performed using regular expression. We can used the pattern to matched all the alphabet and make list with all the matched elements. 

Python3

import re

def Convert(string):

    return re.findall('[a-zA-Z]', string)

str1="ABCD"

print("List of character is : ",Convert(str1))

Output

List of character is : ['A', 'B', 'C', 'D']

Method #4: Using list comprehension 

Python3

s="Geeks"

x=[i for i in s]

print(x)

Output

['G', 'e', 'e', 'k', 's']

Method #5: Using enumerate function 

Python3

s="geeks"

x=[i for a,i in enumerate(s) ]

print(x)

Output

['g', 'e', 'e', 'k', 's']

Method #6: Using json

Python3

import json

stringA = '["geeks", 2,"for", 4, "geeks",3]'

res = json.loads(stringA)

print("The converted list : \n",res)

Output

The converted list : ['geeks', 2, 'for', 4, 'geeks', 3]

Method #7: Using ast.literal

Python3

import ast

ini_list = '["geeks", 2,"for", 4, "geeks",3]'

res = ast.literal_eval(ini_list)

print(res)

print(type(res))

Output

['geeks', 2, 'for', 4, 'geeks', 3] <class 'list'>

Method #8: Using lambda function

Python3

s="Geeks"

x=list(filter(lambda i:(i in s),s))

print(x)

Output

['G', 'e', 'e', 'k', 's']

Method #9: Using map() 

Python3

s="Geeks"

x=list(map(str,s))

print(x)

Output

['G', 'e', 'e', 'k', 's']


How do you convert a string to an array in Python?

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.

How do you convert a string into an array?

In Java, there are four ways to convert a String to a String array:.
Using String. split() Method..
Using Pattern. split() Method..
Using String[ ] Approach..
Using toArray() Method..

Is string an array in Python?

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Can you convert a string to a list in Python?

Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are part of the list elements too.

Chủ đề