Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string representation of a list without double quoted elements to an actual list?

Tags:

python

string

I have referred to many sources but most use json.loads() or ast.literal_eval() which doesn't work for my case:

x = '[(0.0, 58.099669), 56565, Raining]'

Intended output:

x = [(0.0, 58.099669), 56565, 'Raining']

Is there any workaround for this?

like image 237
Weiting Chen Avatar asked Dec 12 '20 01:12

Weiting Chen


People also ask

How do I convert a string to a list without splitting in Python?

One of these methods uses split() function while other methods convert the string into a list without split() function. Python list has a constructor which accepts an iterable as argument and returns a list whose elements are the elements of iterable. An iterable is a structure that can be iterated.

How do I convert a string to a data list in Python?

The split() method is the recommended and most common method used to convert string to list in Python.

How to convert string to list in Python?

Here are the different ways to convert string representation into lists. 1. Using split () and strip () In this approach, we use strip function to remove the square brackets at the ends of string representation of lists. Then we use split () function to split the remaining string by comma, into an array that is basically a list in python.

Is there a string representation of a list in a CSV?

@Tomerikoo string representation of list is exactly the same only it's in the file. No. A string representation of a list is " ['1', '2', '3']". When you read a csv file with csv.reader, each line is ['1', '2', '3']. That is a list of strings. Not a string representation of a list...

What are the different types of literal structures in Python?

The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, and None. Per comment below, this is dangerous as it simply runs whatever python is in the string. So if someone puts a call to delete everything in there, it happily will.

How do I return a list of the words in a string?

The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.


Video Answer


1 Answers

What about this:

class default_key(dict):
    def __missing__(self, key):
        return key

d = default_key()
x = '[(0.0, 58.099669), 56565, Raining]'

res = eval(x, d, {})
# res = [(0.0, 58.099669), 56565, 'Raining']

Explanation: eval normally uses the globals() and locals() dict. However if you don't provide locals() and replace globals() with a dict that returns the name of a key when a lookup is done (and the key isn't found), then every 'variable' name in the given list will be converted to a string when eval is called.

This could still be unsafe however. See this.

like image 79
ssp Avatar answered Oct 25 '22 23:10

ssp