-1

Assume that you have string x as below:

x="['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']"

How to convert x to a list of strings in python?

['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']
burcak
  • 859
  • 6
  • 21

5 Answers5

2

Try:

import ast
list_ = ast.literal_eval(x)
print(list_)

output:

['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']
sarartur
  • 1,048
  • 1
  • 3
  • 12
  • Is ast a common package? What does it stand for? Thanks – burcak Feb 05 '21 at 06:00
  • Yes, it comes with python. It stands for Abstract Syntax Trees. See [docs](https://docs.python.org/3/library/ast.html). It is the correct way to handle these types of problems. – sarartur Feb 05 '21 at 06:02
1
x="['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']"

type(eval(x)) # list

eval(x)

output : ['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']

Akash senta
  • 445
  • 5
  • 15
1

you can use this split method

y=x.split(,)

but it will not split perfectly first you should remove the bracket and spaces like this

x = x.replace('[','')
x = x.repalce(']','')
x = x.replace(' ','')
x = x.replace("'","")
y = x.split(',')

this will do yours work

Rajat Soni
  • 131
  • 11
0

You can try the following

x="['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']"

y = eval(x)

Here :
x is <class 'str'>
y is <class 'list'>

Krishna Chaurasia
  • 8,130
  • 6
  • 18
  • 31
0

You can use eval method. It is simpler!

x="['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']"
print(eval(x))

Output: ['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5', 'aaa6', 'aaa7', 'aaa8']