2

For example, I have a string = "[1,2,3,4]" and I want to only have the [1,2,3,4], I tried doing list(mystring) but it gives me:

['[', '1', ',', '2', ',', '3', ',', '4', ']']

I just want to chop off the "" of the string "[1,2,3,4]".

the output I want can be made with the print, it will output:

[1,2,3,4]

but I don't know how to get that output into a variable, can someone help?

help-info.de
  • 5,228
  • 13
  • 34
  • 35
Tissuebox
  • 914
  • 2
  • 12
  • 31
  • How did you get that string? If it's coming from JSON, you should probably be using the `json` module to load it into a Python list. Otherwise, use Python's own literal parser via `ast.literal_eval`. – PM 2Ring Jun 08 '17 at 18:05
  • I actually get it from " with open("saved_DNA.txt", "r") as f: mypop = f.readline().rstrip() ". there is propably a way to read my text file as a list but right now it works and with ast.literal_eval it output what I need – Tissuebox Jun 08 '17 at 18:09

4 Answers4

5

Use ast.literal_eval:

In [3]: import ast

In [4]: s = "[1,2,3,4]"

In [5]: ast.literal_eval(s)
Out[5]: [1, 2, 3, 4]

In [6]: L = ast.literal_eval(s)

In [7]: L
Out[7]: [1, 2, 3, 4]
inspectorG4dget
  • 97,394
  • 22
  • 128
  • 222
2
In [1]: import json

In [2]: s = "[1,2,3,4]" 

In [3]: json.loads(s)
Out[3]: [1, 2, 3, 4]
Akavall
  • 68,050
  • 39
  • 179
  • 227
2

Use some string functions

s = "[1,2,3,4]"
s_list = [int(x) for x in s.strip('[]').split(',')]
0

You can use list comprehension and check for digits, like:

 s = "[1,2,3,4]"
 lst = [int(x) for x in s if x.isdigit()]

output:

[1, 2, 3, 4]
Mohd
  • 5,075
  • 7
  • 17
  • 29