Home > Back-end >  How to get value in for loop based on certain element
How to get value in for loop based on certain element

Time:02-24

I have a list. I want to get value from the last finished sentence. Like last "." not first, second or third.

lst = ["1st", "2nd", "?", "3rd", ".", "4th", "5th", "6th", ".", "7th", "8th"]

I am trying to achieve

Output: 1st 2nd? 3rd. 4th 5th 6th.

How can I do this by for loop instead of indexing? Indexing won't work because There are unlimited lists and each time last "." position can be different.

CodePudding user response:

If I've gotten your question correctly:

lst = ["1st", "2nd", "?", "3rd", ".", "4th", "5th", "6th", ".", "7th", "8th"]
output = []
start_index = 0
for end_index, char in enumerate(lst):
    if char == ".":
        output.extend(lst[start_index:end_index   1])
        start_index = end_index   1

print(" ".join(output))
  • Related