[Tutor] lstrip() question
Tim Johnson
tim at johnsons-web.com
Mon Feb 2 20:08:08 EST 2004
* Simoni, Bill <WRSimoni at MAPLLC.com> [040202 13:22]:
> > Hello All:
> > I'd like to remove all leading occurance of a html break tag
> > in a string such that
> > "<br><br>test" => "test"
> > and
> > "<br>test<br>this" =>"test<br>this"
>
>
> Hi Tim,
> off the top of my head, I came up with this:
>
> >>> def repstrip(s, sub):
> if s.startswith(sub):
> s = repstrip(s[len(sub):], sub) #strip the leading characters that match and try it again
> return s
>
> >>> print repstrip('real estate broker courtesy', '<br>')
> real estate broker courtesy
>
> >>> print repstrip('<br>real estate broker courtesy', '<br>')
> real estate broker courtesy
>
> >>> print repstrip('<br><br>real estate broker courtesy', '<br>')
> real estate broker courtesy
>
> >>> print repstrip('<br><br>real estate <br> broker courtesy', '<br>')
> real estate <br> broker courtesy
Hi Bill: I liked that, so I modified it to the following:
# ==========================================================================================================
def repstrip(st, substr, reps=0):
s = st.lower()
sub = substr.lower()
if s.startswith(sub):
reps = reps + 1 # keep track of number of replacements
reps,s = repstrip(s[len(sub):], sub, reps) #strip the leading characters that match and try it again
return reps,st[(reps * len(sub)):]
# This allows me to reconstruct the leading tags.
--
Tim Johnson <tim at johnsons-web.com>
http://www.alaska-internet-solutions.com
More information about the Tutor
mailing list