1

I wrote code that is supposed to find the index of all the occurrences of a substring within a string, print them on the same line, and add a comma in between. I was not allowed to use lists, so I came up with the following:

string = input("Enter your string: ")
substring= input("Enter your substring: ")
print("Substring found at positions: ", end = "")

count = 0
while True:
   count = string.find(substring, count+1)
   if count == -1:
      break
   else:
      print(str(count) + ",", end = " ")

However, I need to get rid of the last comma at the end, but I cannot figure out how without using a list. Any insight?

  • Please show a minimal reproducible example including your expected output – Luke Oct 04 '21 at 07:48
  • You could build-up a string by concatenation (instead of printing the individual items), then strip the very last comma of that string before printing. – 9769953 Oct 04 '21 at 07:50
  • Does this answer your question? [How to remove the last comma?](https://stackoverflow.com/questions/53144571/how-to-remove-the-last-comma) – Tomerikoo Oct 04 '21 at 08:15

4 Answers4

0

As user 9769953 explained. You can build up a string through concatenation and then remove the last comma when no other occurrences of the substring have been found:

string = input("Enter your string: ")
substring= input("Enter your substring: ")
print("Substring found at positions: ", end = "")

count = 0
result = ''
while True:
   count = string.find(substring, count+1)
   if count == -1:
      result = result[:-1]
      break
   else:
      result += str(count) + ","

print(result)

Example stdout:

Enter your string: 123451234512345
Enter your substring: 5
Substring found at positions: 4,9,14
ChrisOram
  • 1,079
  • 1
  • 4
  • 16
0

Alternatively, sticking with your same logic:

string = input("Enter your string: ")
substring= input("Enter your substring: ")
print("Substring found at positions: ", end = "")

count = 0
last = ""
while True:
   if last:
      print(last + ", ", end="")
   count = string.find(substring, count+1)
   if count == -1:
      break
   else:
      last = str(count)
print(last)

This paradigm is a little verbose here, but it is very useful when building line-by-line parsers.

For Completeness

Since 'lists are forbidden' this is some kind of exercise. Technically this doesn't use a list:

posns = ", ".join(str(x) for x in range(len(string)) if string[x:].startswith(substring))
print(f"Substring found at positions: {posns}.")

I took that iterator from this question. As noted there it's quadratic in complexity, but it was the most readable one-liner. In practice I would use a proper generator, since it's easier to read. Somehow I don't think they expect you to solve it like this...

2e0byo
  • 4,321
  • 1
  • 3
  • 22
0

You could use a string and concatenate the position values to it and then strip off the last comma and space using string slicing:

string = input("Enter your string: ")
substring= input("Enter your substring: ")
print("Substring found at positions: ", end = "")

count = -1 #We have to start with -1 and not 0 to check the 1st index of string
pos = "" #To store the position values
while True:
    count = string.find(substring, count+1)
    if count == -1:
        pos = pos[:len(pos)-2] #This strips off the last comma and space while exiting the loop
        break
    else:
        pos += f"{count}, " #This is where we concatenate the position values

print(pos)
Sobhan Bose
  • 114
  • 8
0

Just change the prints to append ", NUM" to the line instead of "NUM, ".

It is easier to get rid of the first comma than the last comma, because it is known in advance if the print is going to be called for the first time or not:

count = 0
comma = False
while True:
   count = string.find(substring, count+1)
   if count == -1:
      break
   else:
      if comma:
          print(", ", end = "")
      else:
          comma = True
      print(str(count), end = "")

BTW, you don't need else after break (or return). Also str(x) is not needed in print, you can directly print(x). And the initial value of count should be -1 to start the first search from the very beginning at position 0. Don't forget to print a newline after the loop.

VPfB
  • 12,212
  • 1
  • 34
  • 61