Kenneth D. White
Kenneth D. White

Reputation: 23

Delete Everything before first occurance of X in a string list

I'm stuck on something, I have a string list that is filled similar to this:

['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf','asdf']

This list changes constantly, but the one constant is that 'asdf' will always be there, the data before the first asdf and after it is what changes.

My issue is I either need to Remove all the strings in the list BEFORE the first asdf (in the example it would be one and two) or count everything After the first asdf.

I'm using:

data2 = normalize_line_endings(data)
data3 = data2.split('\n')
data3 = list(map(lambda x: str(x) if x else 'asdf' , data3))
print(data3)
target_ibdex = data3.rindex('asdf')
target_ibdex2 = target_ibdex
print(data3[:target_ibdex - target_ibdex2])

However when it runs, its using the very last asdf, so it just deletes the entire string.

I need:

a=['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf','asdf']
b = code to delete everything before FIRST asdf
len(b)
where b's value is now 8 instead of 10. since one,two got removed.

Upvotes: 2

Views: 40

Answers (2)

Stephen Rauch
Stephen Rauch

Reputation: 49784

You can use list.index() like:

Code:

b = a[a.index('asdf'):]

Test Code:

a = ['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff',
     'asdf', 'asdf']

b = a[a.index('asdf'):]
print(b)

Results:

['asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf', 'asdf']

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

This is a perfect use-case for itertools.dropwhile, if you actually need the elements after:

In [1]: a = ['one', 'two', 'asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf','asdf']

In [2]: import itertools

In [3]: list(itertools.dropwhile(lambda x: x != 'asdf', a))
Out[3]: ['asdf', 'asdf', 'stuff', 'other', 'asdf', 'other stuff', 'asdf', 'asdf']

Of course, if you just need the count of elements after, you can simply do:

In [4]: len(a) - a.index('asdf')
Out[4]: 8

Upvotes: 1

Related Questions