Link to home
Start Free TrialLog in
Avatar of pingeyeg
pingeyeg

asked on

Remove last occurrence of characters

I am trying to figure out how to remove the last occurrence of a string of characters at the bottom of a file.  I've got the following script, but it's not doing as requested.  Any ideas would be greatly appreciated.

iter = r"(\*)+"
found = re.findall(iter, finalOutput)[-1]
finalOutput.replace(found, "")

Open in new window


The code I'm running this on is:

*******************************
text
*******************************
<code>

*******************************
text
*******************************
<code>

*******************************
text
*******************************
<code>

*******************************  <-- this line

I want to remove only the last set of *'s.
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Try this, assuming you can operate on the string as a single value:

mypattern = r"\*+\s*$"
mystring = mystring.replace(mypattern, "")

Open in new window


I also allowed for space characters after the last * characters, just in case there are some.
Could you please clarify:

You  have a huge string spanning multiple lines.

You want to find the last occurence of one or more stars and replace them with nothing?

Do these stars have to be in a separate line?
could there be whitespace before or after these stars?
could there still be some text / code after these stars??
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pingeyeg
pingeyeg

ASKER

TerryAtOpus: Unfortunately, that still leaves the last bit of *'s at the bottom.

gelonida: No space or new lines after the *'s at the bottom.  There are new lines before the *'s.  No text after the *'s either.
Thanks guys!