String comparison

Bengt Richter bokr at
Fri Aug 23 17:13:56 CEST 2002

On Thu, 22 Aug 2002 10:00:02 -0500, "David Iungerich" <david.iungerich at> wrote:

>There was some whitespace junk in the file.  The following works fine.
If you have no explanation for the "whitespace junk," you might want to find one
before it bites you again. On windows, it makes a difference if you open a file with
'r' vs 'rb' mode. Likewise when you open the file to write the data (it also
depends on how you write it). The data retrieved via urllib will probably be
verbatim binary as produced by the source, and HTML line endings may vary ('\r\n' vs '\n' vs '\r')
(e.g., try urllib.urlopen('http://xxx/').read() with xxx == vs

 >>> import urllib
 >>> ms=urllib.urlopen('').read()
 >>> py=urllib.urlopen('').read()
 >>> ms[:72]
 '<!--TOOLBAR_EXEMPT-->\r\n<HTML>\r\n<HEAD>\r\n<META HTTP-EQUIV="Content-Type" C'
 >>> py[:72]
 '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n<?xml-st'

>	try:
>		postReply = urllib.urlopen("",
>		f = open("D:\PythonServerMonitor\KWE1144589.dat","r")
This only worked because 1) you noticed that the backslashes don't work as escapes
unless in front of a few special characters (i.e., a,b,f,n,r,t,v,x),
otherwise you would have used raw string format, presumably, and,

2) You opened the file with 'r', and the data you got via urllib for comparison contained
only '\n' line terminators, not '\r\n' or you recorded the file with 'w' mode and thus stuffed
'\r\n' in place of '\n' on recording and the read did the opposite, or you running on unix, and so
is the data source, so both read and write were effectively in binary, or you took care of
the "whitespace junk" some other way.

>		controlData =
>		f.close()
>		print "     <ControlData>" + str(len(controlData)) + "</ControlData>"
>		print "     <ServerData>" + str(len(postReply)) + "</ServerData>"
>		if (postReply == controlData):
>			response = "<ServerResponseTest>Response - OK</ServerResponseTest>"
>		else:
>			response = "<Result>Server Not Responding</Result>"
>   		# e-mail appropriate party.
>	except Exception:
>		print Exception
That will print you a representation of "Exception." Try it anytime, e.g.,
 >>> print Exception

To get the exception instance and its message if any,
        except Exception, e:
                print e
Note that this except clause will not catch an old fashioned string exception, (raise 'e.g., this')
nor a custom class exception not based on exceptions.Exception.
        except str, s:
                print s #should catch a string exception
                print 'Some other exception happened' # like old custom class-based exception
should tell you more than "print Exception"

>		f.close
>		# e-mail the admin.

BTW, replying to posts at the top annoys many (including me ;-) since it makes threads with
nested quotes hard to follow.

Bengt Richter

More information about the Python-list mailing list