How To transform a string to a list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How To transform a string to a list

Hello I have a string A='['s','c','h',.....]' How To transform To this A=['s','c','h',.....] Thank you

3rd Jan 2020, 9:46 AM
iren yeger
iren yeger - avatar
10 Answers
+ 7
Atleast you could use eval function. eval("['1', '8', '9']") Evaluates to ['1', '8', '9'] But because some developers discourage using of eval function, I'll offer another way: 💩💩💩💩💩💩💩💩💩💩💩💩 💩 💩 💩 A = A[2:-2].split(',') 💩 💩 (this method is 💩) 💩 💩💩💩💩💩💩💩💩💩💩💩💩
3rd Jan 2020, 9:56 AM
Seb TheS
Seb TheS - avatar
+ 9
Something like this (demo): https://code.sololearn.com/c0KVuHpstBaL
3rd Jan 2020, 1:07 PM
David Ashton
David Ashton - avatar
+ 6
Alexander You don't need to use list( ). .split automatically converts the result as list. But the problem with that method is that the list A contained strings. You would get a list of strings, where each string gets double amount of quotes. ['1', '2', '3'][1:-1].split(', ') would evaluate to: ['\'1\'', '\'2\'', '\'3\''] You could fix it with: ['1', '2', '3'][2:-2].split('\', \'') And get: ['1', '2', '3'] But the problem is that you might not know: -How many spaces is used to separate the items. -Which quotes were used. Because of those 2 problems using split method would not be good for this problem.
3rd Jan 2020, 10:23 AM
Seb TheS
Seb TheS - avatar
+ 4
iren yeger A[1:-1] strips the squarebrackets, .split makes the string a list using certain separators. (In the sample it used comma character , as separator, but it could have caused problems, if: -The items also had ",". -The items were separated with different amount of spaces. These would have caused problems with the method: '["5", "4","3"]' #Different separators ", " and ",". A[1:-1].split(",") would return ["5", " 4", "3"] '["8,", "7", "2"]' #An item had ",". A[1:-1].split(",") would return ["8", ""] ... Ok it was a bad method. I think to get a better way than eval, it could require 100 lines code.
3rd Jan 2020, 10:11 AM
Seb TheS
Seb TheS - avatar
+ 4
consider using a regular expression, promise you... much easier to do. (use re.findall)
3rd Jan 2020, 12:14 PM
rodwynnejones
rodwynnejones - avatar
+ 2
iren yeger Is that right? a='[a, b, c]' a=list(a[1:-1].split(', '))
3rd Jan 2020, 10:02 AM
Oleksandr
Oleksandr - avatar
+ 2
3rd Jan 2020, 10:25 AM
iren yeger
iren yeger - avatar
+ 1
Seb TheS Really ... necessary anticipate👍
3rd Jan 2020, 10:40 AM
Oleksandr
Oleksandr - avatar
+ 1
Just simple with use of slipt function. Split function takes from where you want to slipt it into list as parameter
4th Jan 2020, 5:28 PM
deepam aggarwal
deepam aggarwal - avatar
0
Seb TheS Thank you it works. But please can you explain me what does the second method
3rd Jan 2020, 10:01 AM
iren yeger
iren yeger - avatar