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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gesqo
    New Member
    • Nov 2012
    • 7

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

    I have a large text file.
    Several chunks of it are delimited by a pair of small strings:
    "...zczjczjsstr1pqcqdiocpqsstr2ufusvsdvnvvsstr1nnfnenefenzzezf zefsstr2ydgyrger..."
    How could I loop over the text file and delete what appears repeatedly between sstr1 and sstr2?
    The result should be:
    "...zczjczjufus vsdvnvvydgyrger ...".
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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 = "...zczjczjufus vsdvnvvydgyrger ...".

    Comment

    Working...