Reputation: 97
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, 95, 100, 59, 80, 87]\n'
Using .strip()
it gets rid of the \n
, so it becomes:
'[24, 72, 95, 100, 59, 80, 87]'
I think using split would be useless, because using split(' ')
would yield:
['[24, 72, 95, 100, 59, 80, 87]']
Which I think just deepens the complications. What is an effective way to turn this 'string list' into a real list I could use a for loop with? I've been trying for a few hours already, and can't figure it out.
Upvotes: 1
Views: 202
Reputation: 363
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(', ')]
Upvotes: 0
Reputation: 4304
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)
Upvotes: 3
Reputation: 251041
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.
Upvotes: 2
Reputation: 34677
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....
Upvotes: 0