rggod
rggod

Reputation: 629

removing whitespace and \n from list in python?

list1= ['34 5\n', '67 37\n', '40 33\n', '99 100\n', '55 22'] 

the above is the list that i have, how can i make that to

['34','5','67','37','40','33','99','100','55','22']

I want to remove the white space and '\n'. rstrip , strip , replace have been tried but none of the worked

list1.rstrip('\n')
list1.strip('\n')
list1.remove('\n')

Upvotes: 0

Views: 217

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 113988

from itertools import chain
list2 = list(chain.from_iterable(map(str.split,list1)))

you can break this down to be somewhat more readable

flatten_list = chain.from_iterable
list_of_splits = map(str.split,list1) #essentially [s.split() for s in list1]
list2 = flatten_list(list_of_splits)

Upvotes: 1

Cam
Cam

Reputation: 478

list2 = []
for item1 in list1:
    split_list = " ".split(item1)
    for item2 in split_list:
        list2.append(item2.rstrip())

Upvotes: 0

senshin
senshin

Reputation: 10360

Use a pair of nested list comprehensions, the inner of which splits the strings on whitespace and the outer of which merges the nested lists together.

>>> list1= ['34 5\n', '67 37\n', '40 33\n', '99 100\n', '55 22']
>>> [x for sublist in [s.split() for s in list1] for x in sublist]
['34', '5', '67', '37', '40', '33', '99', '100', '55', '22']

Or, if this isn't to your liking, do it with loops instead. (This is probably clearer than a nested list comprehension, come to think of it.)

>>> result = []
>>> for s in list1:
    for num in s.split():
        result.append(num)

>>> result
['34', '5', '67', '37', '40', '33', '99', '100', '55', '22']

Upvotes: 7

Related Questions