By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,642 Members | 1,098 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,642 IT Pros & Developers. It's quick & easy.

In Python, loop to delete several substrings delimited by the same pair of substrings

gesqo
P: 7
I have a large text file.
Several chunks of it are delimited by a pair of small strings:
"...zczjczjsstr1pqcqdiocpqsstr2ufusvsdvnvvsstr1nnfnenefenzzezfzefsstr2ydgyrger..."
How could I loop over the text file and delete what appears repeatedly between sstr1 and sstr2?
The result should be:
"...zczjczjufusvsdvnvvydgyrger...".
Feb 1 '13 #1
Share this Question
Share on Google+
1 Reply

bvdet
Expert Mod 2.5K+
P: 2,851
Assume the text file is in one string and assigned to identifier "s".

1. Initiate a while loop (while True:).
2. Find the character index of "sstr1" (start) and assign to an identifier (use str method find).
3. Find the character index of "sstr2" (end) and assign to an identifier.
4. If either identifier has a value of -1, issue break statement.
5. Else, replace the substring s[startidx:endidx+len(end)] with "" (empty string) and reassign to "s".

You will end up with s = "...zczjczjufusvsdvnvvydgyrger...".
Feb 2 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.