[Tutor] cmp()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 14 Aug 2002 18:25:25 -0700 (PDT)


On Thu, 15 Aug 2002, Kyle Babich wrote:

> > > from sys import *
> > >
> > > arg1 = stdin.readline()[-1:]
> > > arg2 = stdin.readline()[-1:]
> > >
> > > compar = cmp(arg1, arg2)
> > >
> > > if compar == 1:
> > >     print "first greater"
> > > elif compar == 0:
> > >     print "equal"
> > > elif compar == -1:
> > >     print "second greater"
> > > else:
> > >     print "error"
> > > ##########
> > >
> > > So why no matter what I enter it returns that they are equal?
> >
> > Hi Kyle,
> >
> > Can you explain what these two lines are doing?
> >
> > > arg1 = stdin.readline()[-1:]
> > > arg2 = stdin.readline()[-1:]
> >
>
> Taking user input, removing the \n that is put at the end of it by
> default & dumping it into arg1 and arg2.


Are you sure?


(Test out those two statements in the interactive interpreter, and you
should find the bug quickly.  Don't worry, you'll see it quickly.
*grin*)


By the way, a safer way of removing whitespace at the end of the line uses
the rstrip() method on strings.  This is similar to Java's trim()  string
method, but rstrip() just chomps from the right side of a string.

Good luck!