How to Convert Python String to List

0
4813
How To Convert Python String To List and List To String

String and List are among the most used data types in Python. Strings in Python are arrays of bytes representing Unicode characters. Python does not have a built-in character data type, but a single character is simply a string with a length of 1.

Python string to list

To convert string to list in Python, use the string split() method. The split() is a built-in Python method that splits the strings and stores them in the list. Then, it returns a list of the words in the string, using the “delimiter” as the delimiter string.

If the delimiter is not specified in the function argument or is None, then a different splitting algorithm is applied: its runs of consecutive whitespace are regarded as the single separator.

The result will contain no empty strings at the start or end of the string if the string has leading or trailing whitespace.

See the following code example to understand more.

# app.py

def stringToList(string):
    listRes = list(string.split(" "))
    return listRes


strA = "Millie Bobby Brown"
print(stringToList(strA))

See the output.

➜  pyt python3 app.py
['Millie', 'Bobby', 'Brown']
➜  pyt

You can check the data type using the type() function.

# app.py

def stringToList(string):
    listRes = list(string.split(" "))
    return listRes


strA = "Millie Bobby Brown"
print(type(stringToList(strA)))

Output

➜  pyt python3 app.py
<class 'list'>
➜  pyt

Python string to list using strip() and split()

The strip() method returns the copy of a string with both leading and trailing characters removed based on the string argument passed. In addition, the strip() method removes characters from both left and right based on the argument.

See the following code.

# app.py

initial_list = "[11, 21, 29, 46, 19]"
  
print ("initial string", initial_list) 
print (type(initial_list))
  
op = initial_list.strip('][').split(', ')

print ("final list", op)
print (type(op))

Output

➜  pyt /usr/local/bin/python3 /Users/krunal/Desktop/code/pyt/app.py
initial string [11, 21, 29, 46, 19]
<class 'str'>
final list ['11', '21', '29', '46', '19']
<class 'list'>
➜  pyt

So, first, we have defined a string that looks like a list.

Then we use the strip() and split() method to convert the string to a list, and finally, we print the list and its type for double-checking.

Convert using AST(Abstract Syntax Trees) module

Python ast module helps Python applications to process the trees of abstract syntax grammar.

The abstract syntax might change with each Python release; this module helps determine programmatically what the current grammar looks like.

The abstract syntax tree can be generated by passing the ast.

PyCF_ONLY_AST as the flag to the compile() built-in function, or using a parse() helper function provided in this module.

The result will be a tree of objects whose classes all inherit from the ast module.

See the following code example.

# app.py

import ast

# initializing string representation of a list
ini_list = "[11, 21, 19, 46, 29]"

# printing intialized string of list and its type
print("initial string", ini_list)
print(type(ini_list))

# Converting string to list
res = ast.literal_eval(ini_list)

# printing final result and its type
print("final list", res)
print(type(res))

Output

➜  pyt python3 app.py
initial string [11, 21, 19, 46, 29]
<class 'str'>
final list [11, 21, 19, 46, 29]
<class 'list'>
➜  pyt

Python string to list using json.loads()

There is a third way to convert the Python string to a list using json.loads() method.

# app.py

import json

# initializing string representation of a list
initial_list = "[11, 21, 19, 46, 29]"

# printing intialized string of list and its type
print("initial string", initial_list)
print(type(initial_list))

# Converting string to list
op = json.loads(initial_list)

# printing final result and its type
print("final list", op)
print(type(op))

Output

➜  pyt python3 app.py
initial string [11, 21, 19, 46, 29]
<class 'str'>
final list [11, 21, 19, 46, 29]
<class 'list'>
➜  pyt

First, we need to import a json module and then use the json.loads() method to convert the string to a list format.

That’s it for converting Python String to list data type tutorial.

Related Posts

Python String to Int and Int to String

Python dict to json

Python String to Float

Python JSON to CSV 

Python List to JSON

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.