Converting a String Representation of a List into an Actual List Object

Converting a string representation of a list into an actual list object

>>> fruits = "['apple', 'orange', 'banana']"
>>> import ast
>>> fruits = ast.literal_eval(fruits)
>>> fruits
['apple', 'orange', 'banana']
>>> fruits[1]
'orange'

As pointed out in the comments ast.literal_eval is safe. From the docs:

Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the
following Python literal structures: strings, numbers, tuples, lists,
dicts, booleans, and None.

This can be used for safely evaluating strings containing Python
expressions from untrusted sources without the need to parse the
values oneself.

How to convert string representation of list to a list

>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

ast.literal_eval:

With ast.literal_eval you can safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, and None.

Convert string representation of list into list

Assuming your string is a simple list/dict/combination of lists and dicts, you can use one of the two packages mentioned below, listed in order of preference.

json

>>> import json
>>> json.loads('[1, 2, 3]')
[1, 2, 3]

This is definitely the preferred method if you are parsing raw json strings.



ast.literal_eval

>>> import ast
>>> ast.literal_eval('[1, 2, 3]')
[1, 2, 3]

ast.literal_eval will safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets.

Also json.loads is significantly faster than ast.literal_eval. Use this ONLY IF you cannot use the json module first.



yaml

In some cases, you can also use the pyYAML library (you'll need to use PyPi to install it first).

>>> import yaml
>>> yaml.safe_load('[1, 2, 3]')
[1, 3, 4, 6]

Convert string representation of list to list in Python

eval() will consider the given string as python code and return the result. So as per your string, the python code will something like this [万福广场西,凰花苑] which means two variable 万福广场西 and 凰花苑 are in a list.

If you want it to be evaluated as a list of strings you need to bound both strings with double quotes (") such as

'["万福广场西","凰花苑"]'.

When you subject this string to eval(), the output would be,

['万福广场西', '凰花苑']

If you want this to happen dynamically, you need to use split and join functions like,

''.join(list('[万福广场西,凰花苑]')[1:-1]).split(',')

which first makes the list of strings given by

list('[万福广场西,凰花苑]')[1:-1] # O/P ['万', '福', '广', '场', '西', ',', '凰', '花', '苑']

then joins all the strings as

''.join(['万', '福', '广', '场', '西', ',', '凰', '花', '苑']) # O/P 万福广场西,凰花苑

and splits the string by comma (,) to create your desired output.

'万福广场西,凰花苑'.split(',') # O/P ['万福广场西', '凰花苑']

Hope you have got what you were searching for. Feel free to comment in case of any clarifications required.

return each string representation in a list of user-defined objects in a new line

Use:

'\n'.join([str(i) for i in class_object_list])

Or:

'\n'.join(map(str, class_object_list))

Converting to/getting original list object from string representation of original list object in python

You can try:

>>> import ast
>>> ast.literal_eval("[1,2,['a','b'],4]")
[1, 2, ['a', 'b'], 4]

How I Convert a string representation of a nested list into a nested list?

Assuming that you have a string like string = "[[1,2,3],[4,5,6]]" and you want to convert it to a list object like lst = [[1,2,3],[4,5,6]], you could simply use the eval method:

lst = eval(string)

How to convert string representation list with mixed values to a list?

You can first use a regex to add quotes around the potential strings (here I used letters + underscore), then use literal_eval (for some reason I have an error with pd.eval)

from ast import literal_eval
df['col_1'].str.replace(r'([a-zA-Z_]+)', r'"\1"', regex=True).apply(literal_eval)

output (lists):

0     [2, A]
1 [5, BC]


Related Topics



Leave a reply



Submit