DISCLAIMER:
All the other answers are very good suggestions on good practices for storing data and reading them in later, but since you specifically asked how to "convert the string fetched from the text file into a list of integers ...", I will gladly help to do exactly such thing.
However, while this answer may be suitable for the exact thing you requested to be done, it is by no means the best practice to achieve what you want (saving in lists of integers, which would be better off done with JSON or YAML).
SOLUTION
Okay, this seems fairly simple.
You have an original list [10, 21, 42, 5]
.
You save it to a text file, then read it as a list only to find there are two sections (and they're giving back strings + what is that extra 0
?!):
['10, 21, 42, 5', '0']
Seems like you only need the first section, so:
>>> x = ['10, 21, 42, 5', '0']
>>> y = x[0]
>>> print(y)
'10, 21, 42, 5'
>>> print(type(y))
str
But wait, that returns a string! Easy, just split by the separator ", "
:
>>> z = y.split(", ")
>>> print(z)
['10', '21', '42', '5']
Now it returns a list, but it's still a list of strings, so all we got to do is convert every element of the list into type int
(integer). This is easy enough to do with a standard for
loop, but we can make this a one-liner with the map
function:
...
>>> print(z)
['10', '21', '42', '5']
>>> z = map(int, z) # apply int() to every elem; equi. to [int('10'), int('21'), int('42'), int('5')]
>>> print(z)
[10, 21, 42, 5]
>>> print(map(type, z)) # print out type of every element in list
[int, int, int, int]
CONCLUSION
So, given the read-in list of bizarre strings x = ['10, 42, 21, 5', '0']
, you can get your desired list of integers with:
z = map(int, x[0].split(", "))