[Tutor] Better structure?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Feb 2 09:40:56 CET 2005



On Tue, 1 Feb 2005, Jacob S. wrote:

> Also why shouldn't string methods include stuff like lstrip which do
> precisely what I request?


Hi Jacob,

I think the confusion here is that, in Python, strings can be considered a
concrete single thing, but they can also be considered an ordered
collection of characters.  And we might not even care about order.

As a concrete example, we might write a function that sees if something is
a vowel:

###
>>> def isvowel(letter):
...     return len(letter) == 1 and letter in "aeiou"
...
###

Here, we're using a string simply as a collection of characters, but our
definition doesn't really depend on the order of the vowels.



So some functions will use strings merely because they're good containers
of letters.  lstrip() (and rstrip()) are designed so that they consider
their arguments a collection of characters to strip off, but it doesn't
care about the order of the characters.


Admittedly, the documentation of lstrip() doesn't really spell this out
with perfect clarity:

"""
lstrip([chars])

Return a copy of the string with leading characters removed. If chars
is omitted or None, whitespace characters are removed. If given and not
None, chars must be a string; the characters in the string will be
stripped from the beginning of the string this method is called on.
"""

So this can definitely be improved.  The documentation of lstrip() should
emphasize that 'chars' here is used to define the set of characters that
it'll toss out, to keep people aware that it doesn't care about the
sequence-y nature of its input string.



> Maybe because they don't want to bother putting
>
> def mylstrip(string,stripstring):
>     return string[len(stripstring):]


The implementation of rstrip() (the cousin of lstrip()) does come in
really handy when we're dealing with line terminators, since we can
"chomp()" a line by doing:

###
def chomp(line):
    return line.rstrip('\r\n')
###



It is debatable what lstrip() and rstrip() should consider as the common
case.  The library designers decided the behavior they felt would help
people the most, but that may not handle all the ways we might like to use
it.

But, then, that's why we have 'def'.  *grin*



Best of wishes to you!



More information about the Tutor mailing list