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?
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.
The split() method is the recommended and most common method used 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.
@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...
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.
The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With