Python eval string to list

Convert String representation of List to a List in Python

In this tutorial, we will learn about different ways through which we can convert a given String representation of a list to a list object in Python.

Table Of Contents

But first what is What is String Representation of a list?

Here is the difference in below example:

Frequently Asked:

# String Representation of a list str_lst = "[MSD,VK,RS]" # It will print the data type of var str_lst # which is of print( type(str_lst) )

Now you can see how a string representation of a list looks like. We learn about some methods in Python through which we can convert string representaion of a list to a list.

Method 1 : Using split() and strip() method

The split() method of class string is used to split the given string to a list of substrings based on a separator. Whereas the strip() method of class string is used to remove spaces or given characters from the beginning and from the end of string. Here we will be using combination of these two methods, to convert the string representation of a list to a list object.

Читайте также:  Python dataframe get indexes

First we will remove everything before and after the square braces and then use split() method. It will convert the given string representation of a list to a list of substrings. See this Example Code below.

# String representation of list str_lst = "[MSD,VK,RS]" # It will print the data type of var # str_lst which is of print(type(str_lst)) # Strip the open close brackets from string and # then split the string by using comma as delimeter new_lst = str_lst.strip('][').split(', ') print(new_lst) # this will print the type of var new_lst # which happens to be of class list print(type(new_lst))

Here, in code example above, we have successfully converted the string representation of a list into list object using a combination of split() and strip() methods in Python.

Method 2 : Using ast.literal_eval()

Next method that we will be using is the literal_eval() method of ast (Abstract Syntax Tree) module, which comes bundled with Python. The literal_eval() recieves only one parameter which is the string, that needs to be evaluated and returns an oject represented by string. We can use this to convert the string representation of list to a list object.

See the example code below :

import ast str_lst = "[7,18,45]" # It will print the data type of var str_lst # which is of print(type(str_lst)) # Convert string representation of list into a list new_lst = ast.literal_eval(str_lst) print(new_lst) # It will print the type of var new_lst # which happens to be of class list print(type(new_lst))

As you can see in code and output above, we have successfully converted string representation of a list into list using literal_eval() method. This method will not work if items in list are of string class as it will throw an error ValueError. So this function must be used with int or float class types.

Method 3 : Using json.loads()

Next method we will be using is loads() method of the json module in Python. The json stands for Javascript Object Notation, which is a language independent format used to store data.

The loads() method recieves five parameters :

  • first is string which needs to be parsed.
  • second is object_hook(optional), which is used when parsed string is object literal.
  • third is parse_float(optional), which is used when JSON float needs to be decoded.
  • fourth is parse_int(optional), which is used when JSON int needs to be decoded.
  • object_pairs_hook(optional), which is used when when object literal needs to be decoded.

Here we need to convert the given string only to list, so we will pass only string as an argument. See the example below :

import json str_lst = "[7,18,45]" # It will print the data type of var str_lst # which is of print(type(str_lst)) # Convert string representation of list into a list new_lst = json.loads(str_lst) print(new_lst) # It will print the type of var new_lst # which happens to be of class list print(type(new_lst))

In code above, you can see the type of var new_lst is of class list, so we have successfully converted the given string representation of the list to list using loads() method of json module.

Summary

In this article, we have seen three different methods through which we can convert string representation of a list to a list using Python Programming language. First method can be used with every data type, in second method you need to provide int or float and in third method you can provide ever data type with specific optional argument to prevent any kind of errors. You can always use any of the methods above according to your need.

Also we have used Python 3.10.1 for writing examples. Type python –version to check your python version. Always try to write & understand example codes. Happy Coding.

Источник

Python eval string to list

Last updated: Feb 21, 2023
Reading time · 5 min

banner

# Convert string representation of List to List in Python

Use the ast.literal_eval() method to convert the string representation of a list to a list.

The ast.literal_eval() method allows us to safely evaluate a string that contains a Python literal.

Copied!
from ast import literal_eval my_str = '[1,2,3,4]' # ✅ convert string representation of list to list (ast.literal_eval()) my_list = literal_eval(my_str) print(my_list) # 👉️ [1, 2, 3, 4] print(type(my_list)) # 👉️

convert string representation of list to list

The example uses the ast.literal_eval() method to convert the string representation of a list to an actual list object.

The ast.literal_eval method allows us to safely evaluate a string that contains a Python literal.

Alternatively, you can use the str.strip() method to remove the brackets.

# Convert string representation of List to List using strip()

This is a three-step process:

  1. Use the str.strip() method to remove the brackets.
  2. Split the string on each comma.
  3. Optionally, convert each list element to an integer.
Copied!
my_str = '[1,2,3,4]' my_list = [int(item) for item in my_str.strip('[]').split(',')] print(my_list) # 👉️ [1, 2, 3, 4]

convert string representation of list to list using strip

The str.strip method returns a copy of the string with the specified leading and trailing characters removed.

# Converting a String of quoted list elements to a List

If you have a string containing quoted elements, use the str.replace() method to remove the unnecessary quotes.

Copied!
my_str = '["a", "b", "c"]' my_list = my_str.strip('[]').replace('"', '').split(', ') print(my_list) # 👉️ ['a', 'b', 'c']

We used the str.replace() method to remove the double quotes from the string before calling the str.split() method.

# Converting a JSON string to a Python list

If you have a valid JSON string, you can also use the json.loads() method to convert the string representation of the list to a native Python list.

Copied!
import json my_str = '["a", "b", "c"]' my_list = json.loads(my_str) print(my_list) # 👉️ ['a', 'b', 'c'] print(type(my_list)) # 👉️

The json.loads method parses a JSON string into a native Python object.

This approach also works for arrays containing numbers.

Copied!
import json my_str = '[1, 2, 3, 4]' my_list = json.loads(my_str) print(my_list) # 👉️ [1, 2, 3, 4] print(type(my_list)) # 👉️

If the data being parsed is not a valid JSON string, a JSONDecodeError is raised.

Note that this approach only works if you have a valid JSON string.

If there are nested strings wrapped in single quotes, this wouldn’t work.

In that case, you should use the str.replace() method to remove the unnecessary quotes before splitting the string on each comma.

# Converting the string representation of a list to a list using re.findall()

You can also use the re.findall() method to convert the string representation of a list to a list.

Copied!
import re my_str = '[1, 2, 3, 4]' list_of_strings = re.findall(r'3+', my_str) print(list_of_strings) # 👉️ ['1', '2', '3', '4'] list_of_integers = [int(item) for item in list_of_strings] print(list_of_integers) # 👉️ [1, 2, 3, 4]

The same approach can be used if your list contains strings.

Copied!
import re my_str = '["ab", "cd", "ef", "gh"]' list_of_strings = re.findall(r'\w+', my_str) print(list_of_strings) # 👉️ ['ab', 'cd', 'ef', 'gh']

The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.

If your list contains numbers, use the following regular expression.

Copied!
import re my_str = '[1, 2, 3, 4]' list_of_strings = re.findall(r'7+', my_str) print(list_of_strings) # 👉️ ['1', '2', '3', '4']

The square brackets [] are called a character class and match the digits in the specified range.

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the digits range).

  • characters that can be part of a word in any language
  • numbers
  • the underscore character

# Converting the string representation of a list to a list using eval()

You can also use the eval() function to convert the string representation of a list to a list.

Copied!
my_str = '[1, 2, 3, 4]' my_list = eval(my_str, '__builtins__': None>, >) print(my_list) # 👉️ [1, 2, 3, 4] print(type(my_list)) # 👉️

However, note that using eval with user-supplied data isn’t safe.

Instead, you should use the safer alternative — ast.literal_eval .

Copied!
from ast import literal_eval my_str = '[1,2,3,4]' my_list = literal_eval(my_str) print(my_list) # 👉️ [1, 2, 3, 4] print(type(my_list)) # 👉️

# Converting the string representation of a list to a list using map()

You can also use the map() function to convert the string representation of a list to a list.

Copied!
my_str = '[1, 2, 3, 4]' my_list = list(map(int, my_str[1:-1].split(','))) print(my_list) # 👉️ [1, 2, 3, 4]

If you have a list of strings, use the str.replace() method instead of map() .

Copied!
my_str = '["ab", "cd", "ef", "gh"]' my_list = list( map( lambda x: x.replace('"', ''), my_str[1:-1].split(',') ) ) print(my_list) # 👉️ [1, 2, 3, 4]

We used string slicing to exclude the first and last characters from the string (the brackets) and split the string on each comma.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We passed the int() class to the map() function, so it gets called with each number from the list of strings.

# Converting the string representation of a list to a list using PyYAML

You can also use the PyYAML module to convert the string representation of a list to a list.

First, make sure you have the PyYAML module installed by running the following command.

Copied!
pip install PyYAML # 👇️ or with pip3 pip3 install PyYAML

Now you can import and use the PyYAML module.

Copied!
import yaml my_str = '[1, 2, 3, 4]' my_list = yaml.safe_load(my_str) print(my_list) # 👉️ [1, 2, 3, 4]

The PyYAML module can also be used if your list contains strings.

Copied!
import yaml my_str = '["ab", "cd", "ef", "gh"]' my_list = yaml.safe_load(my_str) print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh']

The yaml.safe_load() method loads a subset of the YAML language. This is recommended for loading untrusted input.

There is also a yaml_full_load method that you can use if you trust the data that’s being parsed.

Copied!
import yaml my_str = '[1, 2, 3, 4]' my_list = yaml.full_load(my_str) print(my_list) # 👉️ [1, 2, 3, 4]

The yaml.full_load() method takes a YAML document, parses it and produces the corresponding Python object.

Note that using the full_load() method with untrusted input is not recommended.

If you work with untrusted data, use the yaml.safe_load() method instead.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью