0

Good evening,

I have a python variable like so

myList = ["['Ben'", " 'Dillon'", " 'Rawr'", " 'Mega'", " 'Tote'", " 'Case']"]

I would like it to look like this instead

myList = ['Ben', 'Dillon', 'Rawr', 'Mega', 'Tote', 'Case']

If I do something like this

','.join(myList)

It gives me what I want but the type is a String

I also would like it to keep the type of List. I have tried using the Join method and split method. And I have been debugging use the type() method. It tells me that the type in the original scenario is a list.

I appreciate any and all help on this.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Taner
  • 75
  • 7
  • 3
    Where is that strange list coming from? Can you fix it to produce proper JSON so you don't have to do this? – Barmar Aug 24 '22 at 21:44
  • @Barmar When I send data through postman to my Python backend, It gets transformed to that becomes it comes in as an list already. Our frontend sends the data as a string so we dont have the issue. Definitely something to look into more – Taner Aug 24 '22 at 21:52
  • Either there's a problem with how you're parsing it in the Python backend, or you're formatting it incorrectly in postman. – Barmar Aug 24 '22 at 21:56
  • I am thinking It is with Postman because when I send it from the frontend It works fine. I will look into it more If it becomes an issue, and ask another question If I get stuck. – Taner Aug 24 '22 at 22:03

2 Answers2

2

Join the inner list elements, then call ast.literal_eval() to parse it as a list of strings.

import ast

myList = ast.literal_eval(",".join(myList))
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Also can be done by truncating Strings, therefore avoiding the import of ast.

myList[5] = (myList[5])[:-1]
for n in range(0, len(myList)):
    myList[n] = (myList[n])[2:-1]
Kineye
  • 154
  • 7