Search code examples
pythonpython-3.2

How to remove ' ' from my list python 3.2


newlist=['21', '6', '13', '6', '11', '5', '6', '10', '11', '11', '21', '17', '23', '10', '36', '4', '4', '7', '23', '6', '12', '2', '7', '5', '14', '3', '10', '5', '9', '43', '38']

Now what I want to do with this list is take out the ' ' surrounding each integer, the problem is that the split() function or the strip() function wont work. So I don't know how to remove it. Help.

AttributeError: 'list' object has no attribute 'split' is given when I run.

Also After that I want to find the sum of each 7 integers in the list, and that I also don't know where to start. Any help would be appreciated.


Solution

  • What you have is a list of strings (hence the ''s), and you want to convert them to integers. The boring solution to the problem is a simple for loop:

    for i in range(len(newlist)):
        newlist[i] = int(newlist[i]
    

    The more compact method is a list comprehension, which you can read about here: List Comprehensions:

    newlist = [int(num) for num in newlist]
    

    The two functions you mentioned operate only on single strings.

    >>> "Hi my name is Bob".split(" ")
    ["Hi", "my", "name", "is", "Bob"]
    
    >>> "GARBAGE This string is surrounded by GARBAGE".strip("GARBAGE")
    " This string is surrounded by "
    

    As @Tomoko Sakurayama mentioned, you can sum simply enough with another loop. If you're feeling fancy, though, you can use another list comprehension (or even stack it on the old one, though that's not very Pythonic :).

    [sum(newlist[i:i+7]) for i in range(0, len(newlist) - 6, 7)] + [sum(newlist[-(len(newlist) % 7):])]