0

I'm writing a Python code, where I'm truncating the starting part of a large block of text. For that, I wrote the following:

# chatText is the variable where the text block is stored. lbCount is for counting the number of line breaks.
lbCount = 0
i = 0
for character in chatText:
    print(character)
    if (character == '\n'):
        lbCount = lbCount + 1
        print("Number of line breaks seen:", lbCount)
        print("Current position in text:", chatText.index(character))
        # Store the text after the 4th line break.
        if (lbCount == 4):
            i = chatText.index(character)+1
            print("The index from where the chats begin is:", i)
            chats = eval(f"chatText[i:]")
            break

I don't know why, but the chatText.index(character) is always returning 13. This is interesting because that was the intended value from an earlier version of this code. However, if I modify the code as such:

lbCount = 0
i = 0
for character in chatText:
    print(character)
    i = i + 1 # Putting a simple counter variable here, which counts each character encountered.
    if (character == '\n'):
        lbCount = lbCount + 1
        print("Number of line breaks seen:", lbCount)
        print("Current position in text:", chatText.index(character))
        if (lbCount == 4):
            print("The index from where the chats begin is:", i)
            chats = eval(f"chatText[i:]")
            break

It gives the intended value (117 in my case), and the required block of text is stored in chats variable. The chatText.index(character) still gives the value 13 in this case too. I was wondering about why is this happening. I haven't restarted my computer yet, so I don't know if it's a cache issue or something (using the term loosely here).

Nogdev
  • 59
  • 12
  • Have you tried reading the documentation for `.index`? This behavior will be clear – DeepSpace May 13 '21 at 17:24
  • 1
    `index(char)` returns the index of the *first occurrence* of char in your string. It doesn't intuit that you mean a particular occurrence that you've got to in your loop. If you want the index you've got to in your loop, use `enumerate`. – khelwood May 13 '21 at 17:24
  • @khelwood Argh! I was under the impression that it'd give me the *current* index of the character being read, and not the first occurence. Thanks for the quick reply :D. – Nogdev May 13 '21 at 17:29

0 Answers0