Convert string representation of list to a list in Python

This text is very helpful for you if you want to acquire skills in the methods of converting a string presentation of a list to a list in Python programming. In this blog, some of the methods for conversion of the string representation of a list to a list have been discussed very clearly. So, read the text below very carefully to learn and explore.

Using split() and strip() method :

The two methods mentioned above are one of the most important aspects of Python programming when it comes to manipulating strings. Using the split() method, you can convert each word of a string into a list element and use strip() to remove unwanted spaces at the beginning and end. With the help of this method first, initialize the string representation of a list then print the list and its type. after this convert the string to a list and finally print the output and its type.

For Example:

# initialize string representation of a list
list = "[3, 4, 5, 6, 7]"
  
# print the initialized string of list and its type
print ("initial string", list)
print (type(list))
  
# Convert the string to list
res = list.strip('][').split(', ')
  
# print the output and its type
print ("final list", res)
print (type(res))

Output:

string [3, 4, 5, 6, 7]
<class 'str'>
final list ['3', '4', '5', '6', '7']
<class 'list'>

 

Using json.loads() method:

This is another method to convert the string representation of list to a list in Python. By using this method firstly import json which is the built-in package in Python then create the string representation of a list and print the list and its type and after this convert the string to the list using json.loads() method and finally print the result and its type. The code demonstration of this method is given below.

#import json
import json
  
# initialize string representation of a list
list = "[3, 4, 5, 6, 7]"
  
# print the initialized string of list and its type
print ("initial string", list)
print (type(list))
  
# Convert the string to list
res = json.loads(list)
  
# print the result and its type
print ("final list", res)
print (type(res))

Output:

initial string [3, 4, 5, 6, 7]
<class 'str'>
final list [3, 4, 5, 6, 7]
<class 'list'>

 

Leave a Reply

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