+ 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
10 Respostas
+ 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 💩) 💩
💩💩💩💩💩💩💩💩💩💩💩💩
+ 9
Something like this (demo):
https://code.sololearn.com/c0KVuHpstBaL
+ 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.
+ 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.
+ 4
consider using a regular expression, promise you... much easier to do. (use re.findall)
+ 2
iren yeger Is that right?
a='[a, b, c]'
a=list(a[1:-1].split(', '))
+ 1
Seb TheS Really ... necessary anticipate👍
+ 1
Just simple with use of slipt function. Split function takes from where you want to slipt it into list as parameter
0
Seb TheS
Thank you it works.
But please can you explain me what does the second method