AppDividend
Latest Code Tutorials

How To Convert Python String To List and List To String

0

In the Python programming language, the data type conversion is the most common operation. In this tutorial, we will see How To Convert Python String To List Tutorial With Example. We will try to convert the given string to list, where spaces or any other special characters.

How To Convert Python string to list

If we need to achieve the string to list operation, then we need to use the Python string split() method.

Python split() method is used to split the strings and store them in the list.

Python built-in method 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 the different splitting algorithm is applied: it runs of consecutive whitespace are regarded as the single separator, and the result will contain no empty strings at a 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 Python 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()

Python strip() method returns the copy of a string with both leading and trailing characters removed based on the string argument passed. 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 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 itself might change with each Python release; this module helps to find out 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 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 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.

How To Convert Python List To String

Using a Python string join() method

There are a few useful methods to convert a Python list to the string.

First, if it is a list of strings, you may use the Python join() function.

# app.py

stcast = ['millie', 'noah', 'finn']
print(type(stcast))

comcast = ', '.join(stcast)

print(comcast)
print(type(comcast))

Output

➜  pyt python3 app.py
<class 'list'>
millie, noah, finn
<class 'str'>
➜  pyt

Python join method is the method that returns the string concatenated with the elements of an iterable.  Python String join() method provides a flexible way to concatenate a string.

In our case, the iterator is the list.

Using the Python string strip() method

Python strip() method returns the copy of a string with both leading and trailing characters removed based on the string argument passed.

In our case, we will pass ‘[ ]’, and we will then convert into the string using Python str() function.

See the following code.

# app.py

stcast = ['millie', 'noah', 'finn']
print(type(stcast))

comcast = str(stcast).strip('[]')

print(comcast)
print(type(comcast))

See the output.

➜  pyt python3 app.py
<class 'list'>
'millie', 'noah', 'finn'
<class 'str'>
➜  pyt

So, we have seen how we can convert string to list and list to string in Python in many ways.

Related Posts

Python string to int and int to string

Python dict to json

Leave A Reply

Your email address will not be published.

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