string stripping issues
Iain King
iainking at gmail.com
Fri Mar 3 07:17:50 EST 2006
Ben Cartwright wrote:
> Ben Cartwright wrote:
> > orangeDinosaur wrote:
> > > I am encountering a behavior I can think of reason for. Sometimes,
> > > when I use the .strip module for strings, it takes away more than what
> > > I've specified. For example:
> > >
> > > >>> a = ' <TD WIDTH=175><FONT SIZE=2>Hughes. John</FONT></TD>\r\n'
> > >
> > > >>> a.strip(' <TD WIDTH=175><FONT SIZE=2>')
> > >
> > > returns:
> > >
> > > 'ughes. John</FONT></TD>\r\n'
> > >
> > > However, if I take another string, for example:
> > >
> > > >>> b = ' <TD WIDTH=175><FONT SIZE=2>Kim, Dong-Hyun</FONT></TD>\r\n'
> > >
> > > >>> b.strip(' <TD WIDTH=175><FONT SIZE=2>')
> > >
> > > returns:
> > >
> > > 'Kim, Dong-Hyun</FONT></TD>\r\n'
> > >
> > > I don't understand why in one case it eats up the 'H' but in the next
> > > case it leaves the 'K' alone.
> >
> >
> > That method... I do not think it means what you think it means. The
> > argument to str.strip is a *set* of characters, e.g.:
> >
> > >>> foo = 'abababaXabbaXabababbbb'
> > >>> foo.strip('ab')
> > 'XabbaX'
> > >>> foo.strip('aabababaab') # no difference!
> > 'XabbaX'
> >
> > For more info, see the string method docs:
> > http://docs.python.org/lib/string-methods.html
> > To do what you're trying to do, try this:
> >
> > >>> prefix = 'hello '
> > >>> bar = 'hello world!'
> > >>> if bar.startswith(prefix): bar = bar[:len(prefix)]
> > ...
> > >>> bar
> > 'world!'
>
>
> Apologies, that should be:
> >>> prefix = 'hello '
> >>> bar = 'hello world!'
> >>> if bar.startswith(prefix): bar = bar[len(prefix):]
> ...
> >>> bar
> 'world!'
>
or instead of:
a.strip(' <TD WIDTH=175><FONT SIZE=2>')
use:
a.replace(' <TD WIDTH=175><FONT SIZE=2>','')
Iain
More information about the Python-list
mailing list