user1899415
user1899415

Reputation: 3125

Python: split elements of a list

As a follow up to this question: split elements of a list in python

Given the list:

l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', '']

How do I get everything after the \t?

I tried:

>>> [i.split('\t', 1)[1] for i in t]                                                                                                                           
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

Is it because I have '' at the end? How do I exclude it?

Upvotes: 4

Views: 950

Answers (2)

smci
smci

Reputation: 33940

Your case is easier, because you can exploit that we throw away everything before the tab:

l = [x.split('\t')[-1] for x in l]
['0238.94', '2.3904', '0139847', '']

Note we used [-1] instead of [1], so we don't blow up with IndexError when we split('', '\t') and only get one group [''] as a result. '-1' means 'the last index', so -1 will be equivalent to 1 when there are 2 split-groups, and 0 when there is only 1.

Upvotes: 4

inspectorG4dget
inspectorG4dget

Reputation: 113905

In [175]: l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', '']

In [176]: [i.partition('\t')[-1] for i in l]
Out[176]: ['0238.94', '2.3904', '0139847', '']

Or, if you only want to consider the elements with a '\t' in them:

In [177]: [i.partition('\t')[-1] for i in l if '\t' in i]
Out[177]: ['0238.94', '2.3904', '0139847']

Upvotes: 5

Related Questions