سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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!.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top