chillbro chillbro - 1 month ago 6
Python Question

Using find function to print line and character location on line

I am a new coder trying to figure out how to use the find() command to search for a chunk of text, word, or letter in a multi-lined code. So if the input was


I like dogs.

I have a dog too.


Then I'm aiming to print something like:


Dog found on line 1 at character 7

Dog found on line 2 at character 9


So far I have

chunk = input('Enter chunk: ')
for line in data.split("\n"): #data is the block of text to be searched
for word in line.split():


(Not sure what to do after this) I have tried

print(word.find(chunk))


but that only outputs the last character that the chunk appears at.

if chunk in i:
print(chunk, 'on line number {} at character {}',x,y)


I know this is how I need to print but am not sure how I establish x and y variables either.

All help appreciated, Thanks!

Answer

If the substring is found within the string, find will return its position. If not, it returns -1. Here is how you can use find:

for j, line in enumerate(data.splitlines()):
    pos = line.find(chunk)
    if pos != -1:
        print('{0} found on line {1} at character {2}'.format(chunk, j, pos))
Comments