I am opening a .txt
file and have to use a list inside of it for a function I am writing. This is one of the lists given in the text file:
\'[24, 72
An answer has already been accepted, but I just wanted to add this for the record. The json module is really good for this kind of thing:
import json
s = '[24, 72, 95, 100, 59, 80, 87]\n'
lst = json.loads(s)
Use ast.literal_eval
:
strs='[24, 72, 95, 100, 59, 80, 87]\n'
list_of_strs = ast.literal_eval(strs)
Further help, leave a comment....
You can use ast.literal_eval
:
In [8]: strs='[24, 72, 95, 100, 59, 80, 87]\n'
In [9]: from ast import literal_eval
In [10]: literal_eval(strs)
Out[10]: [24, 72, 95, 100, 59, 80, 87]
help on ast.literal_eval
:
In [11]: literal_eval?
Type: function
String Form:<function literal_eval at 0xb6eaf6bc>
File: /usr/lib/python2.7/ast.py
Definition: literal_eval(node_or_string)
Docstring:
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
you don't need to go importing anything for this
s = '[24, 72, 95, 100, 59, 80, 87]'
s.translate(None, '[]').split(', ') will give you a list of numbers that are strings
if you want a list of ints try
[int(i) for i in s.translate(None, '[]').split(', ')]