[Tutor] Nested loops/test conditions

Jeff Shannon jeff@ccvcorp.com
Mon, 11 Feb 2002 11:27:59 -0800

> Chris Keelan <rufmetal@rogers.com> wrote:
> def fix_string(badString):     # need this to strip newlines, etc. from a
> readline()
>     goodString = string.split(badString)
>     goodString = string.join(goodString)
>     return goodString

This is a *very* inefficient way to strip newlines.  Depending on your needs, you
can probably do what you want with a simple

goodstring = string.rstrip(badstring)

This will remove all whitespace (space, tab, newline) from the right side of
badstring.  (string.strip() will remove it from both sides.)  This is more-or-less
equivalent to what you're doing already, and will be *much* faster.  (Note also
that for Python 2.x, 'goodstring = badstring.strip()' is also equivalent.)

If you think that you may have significant whitespace at the end of strings, and
want to remove *only* the newline character at the very end, you can do something

def fix_string(badstring):
    if badstring[-1:] == '\n':
    #or (2.x)--    if badstring.endswith('\n'):
        return badstring[:-1]
        return badstring

This checks to see if the last character of the string is a newline, and if so,
returns everything *except* that newline.  If there is no newline at the end, then
the string is returned unchanged.  Using slice notation on the test line prevents
this from blowing up when passed an empty string.  (There was a long discussion on
comp.lang.python, recently, about how best to emulate Perl's chomp function; this
was one of (well... two of) the best contenders.)

Jeff Shannon
Credit International