Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String to list
#1
Consider this string
'[1,2]'
I am trying to convert it to
[1,2]

I tried some string and list functions, but nothing worked.

Looking for a simple way to perform the conversion. Any suggestions welcome.
Reply
#2
You could use eval('[1, 2]'). In some applications that can lead to security flaws, so it gets frowned upon.

Another options is to strip the brackets with slicing and then split on the comma. text[1:-1].split(','). That will give you a list of strings, not a list of ints, but you can convert them to ints with a loop of list comprehension.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
A bit different way:
>>> '[1, 2]'.strip('[]').split(',')
['1', ' 2']
>>> 
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
An obvious answer, create it as a list, [1,2], in the first place.
Reply
#5
There is also a safe eval:
import ast
ast.literal_eval('[1,2]')
or assuming the initial list is json data
import json
json.loads('[1,2]')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I converted string to 'list', but it doesn't look like a list! mrapple2020 3 3,239 Apr-07-2019, 02:34 PM
Last Post: mrapple2020
  Create Alert if string from list appears on other list javalava 1 2,504 Sep-17-2018, 02:44 PM
Last Post: DeaD_EyE
  List of pathlib.Paths Not Ordered As Same List of Same String Filenames QbLearningPython 20 15,335 Nov-16-2017, 04:47 PM
Last Post: QbLearningPython
  Create a new list by comparing values in a list and string DBS 2 3,520 Jan-14-2017, 07:59 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020