string stripping issues
Ben Cartwright
bencvt at gmail.com
Thu Mar 2 17:00:03 EST 2006
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!'
--Ben
More information about the Python-list
mailing list