Search code examples
pythonstringlistreplacestrip

How to remove certain characters from lists (Python 2.7)?


I've got a list where each element is:

['a ',' b ',' c ',' d\n ']

I want to manipulate it so that each element just becomes:

['a','b','c','d']

I don't think the spaces matter, but for some reason I can't seem to remove the \n from the end of the 4th element. I've tried converting to string and removing it using:

str.split('\n')

No error is returned, but it doesn't do anything to the list, it still has the \n at the end.

I've also tried:

d.replace('\n','')

But this just returns an error.

This is clearly a simple problem but I'm a complete beginner to Python so any help would be appreciated, thank you.

Edit:

It seems I have a list of arrays (I think) so am I right in thinking that list[0], list[1] etc are their own arrays? Does that mean I can use a for loop for i in list to strip \n from each one?


Solution

  • >>> my_array = ['a ',' b ',' c ',' d\n ']
    >>> my_array = [c.strip() for c in my_array]
    >>> my_array
    ['a', 'b', 'c', 'd']
    

    If you have a list of arrays then you can do something in the lines of:

    >>> list_of_arrays = [['a', 'b', 'c', 'd'], ['a ', ' b ', ' c ', ' d\n ']]
    >>> new_list = [[c.strip() for c in array] for array in list_of_arrays]
    >>> new_list
    [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]