Search code examples
pythonstringlistintegerliterate-programming

Python - Convert String into Iterable Integer List


I am developing a Twitch Python IRC Bot that has a currency system. The balances of users are stored in a list, which is loaded from and saved to a text file. However, because the text file's content is loading into one singular string that is then placed inside the list, I cannot iterate through each entry in the string to add points to it. For example, here is the iterable list I'm looking for: [10, 21, 42, 5]

But, when this is saved to a text file and then loaded into the list, it turns out like this: ['10, 21, 42, 5', '0' (with a 0 entry added on). As you can see, this would iterate through the list with only recognizing 2 sections, which is where the quotations surround. Is there a way I can convert the string fetched from the text file into a list of integers that I can iterate through? Thanks in advance!


Solution

  • 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(", "))