[Tutor] string.replace

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 11 Sep 2001 21:49:25 -0700 (PDT)


On Tue, 11 Sep 2001, Ignacio Vazquez-Abrams wrote:

> On Tue, 11 Sep 2001, Jon Cosby wrote:
> 
> > >>> from string import *
> > >>> def striptabs(line):
> > ... 	if "<" in line:
> > ... 		l = find(line, "<", 0)
> > ... 		m = find(line, ">", l)
> > ... 		if l and m:
> > ... 			print "Tag found"		# Test
> > ... 		line = replace(line, line[l:m+1], "")
> > ... 		striptabs(line)
> > ... 	else:
> > ... 		return line
> > ... 	return line

> Ypur function has a rather large logic error; it's only find the first
> tag because you only go through the process once. You need to change
> the if to a while and get rid of the embedded call to stribtabs().

The recursive striptabs() call is buggy, but's also intentionally
recursive: if Jon changes the line from:

 		striptabs(line)

to:

                line = striptabs(line)

and corrects a few more logical bugs, the code should work because
striptabs should only call itself recursivly if the line still contains
tags --- his use of recursion is about the same as if he had used an
explicit while loop.

I have a corrected version of it below.  Jon, don't look if you want to
work it out for yourself.

** spoiler space **
















** spoiler space **

Here's a corrected version of Jon's striptabs() function, with some
simplifications to the logic:

###
from string import find, replace
def striptabs(line):
    l = find(line, "<", 0)
    m = find(line, ">", l)
    if l >= 0 and m >= 0:
        line = replace(line, line[l:m+1], "")
        line = striptabs(line)
    return line
###


And a small test case:

###
>>> striptabs('hello world')
'hello world'
>>> striptabs('i have <some tags> <around> me')
'i have   me
###