Click here to Skip to main content
14,828,863 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using Python scripting environment, I am trying to print string index for each string occurrence from a file, The code I have written if as follows:-
#!/usr/bin/env python
import re

file = open("file.txt", "r")
regex = re.compile(r'xy ')

for line in file:
preamble = regex.findall(line)
for word in preamble:
print(""+ str(word))

The output, I am getting is
xy
xy
.
.

But I want index no of each occurrence of pattern xy as [10, 28, 76] occurrence and every new line occurrence for pattern xy of file.txt should be printed in new line.

What I have tried:

#!/usr/bin/env python
import re

file = open("file.txt", "r")
regex = re.compile(r'xy ') 

for line in file:
    preamble = regex.findall(line)
    for word in preamble:
         print(""+ str(word))
Posted
Updated 31-Oct-20 21:53pm

1 solution

Use an indexer instead of a regex. You need to loop over each character of the line of text looking for the substrings. For each find you can print the position or save it to a list.
   
Comments
Senor H 1-Nov-20 7:34am
   
Thanks Richars, but I am newbie and looking for code similar to available at following link.
https://www.geeksforgeeks.org/python-output-formatting/
Above link do the job for strings. I am trying to do the same reading file.
Richard MacCutchan 1-Nov-20 7:38am
   
Sorry but I have no idea what that website does, and I don't plan to go and find out. Whatever it is you are looking for you need to make clear in your question. You can also check 7. Input and Output — Python 3.9.0 documentation[^] for more information.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900