Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split and strip elements in list python

words is a list which look something like this:

        ['34 ', '111110 ', '0 ', '@jjuueellzz down ']
        ['67 ', '111112 ', '1 ', 'Musical awareness ']
        ['78 ', '111114 ', '1 ', 'On Radio786 ']
        ['09 ', '111116 ', '0 ', 'Kapan sih lo ']

If you notice there is a space at the end after every element in the list, I know I should strip but do not know how would I do that.

Here is my code:

words = line.split('\t')

If I do words = line.strip().split('\t') - it does not strip properly like I want

like image 668
fscore Avatar asked Oct 28 '25 16:10

fscore


2 Answers

The simplest approach is probably to replace your first line with something like this:

words = [x.strip() for x in line.split('\t')]

This is a list comprehension, taking each element of the list returned by line.split('\t'), stripping it, and adding it to a new list.

like image 72
Mac Avatar answered Oct 31 '25 07:10

Mac


This is easiest with a list comprehension:

lst = ['34 ', '111110 ', '0 ', '@jjuueellzz down ']
new_lst = [x.strip() for x in lst]

Now I'm not sure that I completely understand your input -- Perhaps you have a list of lists. If that's the case, then you just put one list comprehension inside another:

new_data = [[x.strip() for x in lst] for lst in old_data]

If the original list is the result of line.split('\t'), the answer becomes even easier. Split on any whitespace, not just tabs:

line.split()  # splits on *any* whitespace!.
like image 22
mgilson Avatar answered Oct 31 '25 05:10

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!