2

I have this list of strings

list = ['1', '2', '3', '4', '', '    5', '    ', '    6', '', '']

and I want to get every item after the first empty string to get this result

list = ['    5', '    ', '    6', '', '']

note that I want to leave the empty strings that comes after

I wrote this function:

def get_message_text(list):
    for i, item in enumerate(list):
        del list[i]
        if item == '':
            break
    return list

but I am getting this wrong results for no reason I know:

['2', '4', '    5', '    ', '    6', '', '']

any help ?

2
  • 4
    never change a list while iterating on it Commented Nov 6, 2020 at 22:09
  • Jean-François Fabre, I can see now what I did wrong, thanks Commented Nov 6, 2020 at 22:30

2 Answers 2

5

Just find the index of the first empty string and slice on it:

def get_message_text(lst):
    try:
        return lst[lst.index("") + 1:]
    except ValueError:  # '' is not in list
        return [] # if there's no empty string then don't return anything
Sign up to request clarification or add additional context in comments.

Comments

0

Construct a generator that drops while empty string not yet found.

Use list(get_message_text(lst)) if you need a list,

otherwise use generator in for expression

for e in get_message_text(lst):

def get_message_text(lst):
    output = False
    for e in lst:
        if not output:
            if e == '': output = True
            continue
        yield e

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.