-2

Here, I have a list of ints, strings, and lists:

from types import *
import re
l1 = [3, 'c', 'thisshouldendloop', 'e', ['h', 2, 'p', 'g'], 7, 4, 5]

I want a while loop which prints each list element and stops when it encounters any string containing 'end'. Before stopping, it should print the string containing 'end', as well. Here's what I have:

length = len(l1)
index = 0
while index < length:
  for s in l1:
      if (type(s) == 'int'):
          print(s)
          index += 1
      elif (type(s) == 'string'):
          if re.search('end', s):
              print(s)
              # attempts to end while loop by making index > length
              index += (length * 2)
          else:
              print(s)
              index += 1
      else:
          print(s)
          index += 1

Output:

3
c
thisshouldendloop
e
['h', 2, 'p', 'g']
7
4
5

What output should look like:

3
c
thisshouldendloop
h0tsauce
  • 9
  • 1
  • 1
    Why oh why are you using a while-loop? – Kelly Bundy Feb 03 '22 at 00:28
  • `type(s) == 'string'` is wrong in two ways: 1) the type name is `str`, 2) `type()` returns the type itself, not its name. So `type(s) == str` will work, but the linked duplicate covers better ways. – wjandrea Feb 03 '22 at 00:30
  • Beside the point, but why are you using regex when a simple `'end' in s` would work? – wjandrea Feb 03 '22 at 00:31

1 Answers1

0

You don't need the re module; the in operator will do here. You can also use break to terminate the loop early:

l1 = [3, 'c', 'thisshouldendloop', 'e', ['h', 2, 'p', 'g'], 7, 4, 5]

for item in l1:
    print(item)
    if isinstance(item, str) and 'end' in item:
        break
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33