Home > OS >  Python find index of string with while loop
Python find index of string with while loop

Time:11-06

New to python-

I need to create a "while" loop that searches for the position of a certain string in a text file.

All the characters in the file have been set to integers (x = len(all)), so now I need a loop to search for the index/position of a certain string.

This is where I'm at right now:

string = 'found' 
index = 0 

while index < x:
   if ????

Then it should print out something like

String found between (startIndex) and (endIndex)

CodePudding user response:

You can use the .find() function:

string = "found"
x = "I found the index"
index =  x.find(string)
end = index   len(string)
print(index, end)

2, 7

CodePudding user response:

Python has a built-in function called index that provides this functionality:

string = "found"
with open("FILE", "r") as f:
    for i,j in f.readlines():
        if string in j:
            foo = f.index(string)
            print(f"String found at line {i 1} between ({foo}) and ({foo   len(string)})")
            break
  • Related