473,700 Members | 2,582 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String comparison problem

I am printing these information.

print string.lower(in fo_res[2])
print string.lower(md 5sum(f_md5))
print len(string.lowe r(info_res[2]))
print len(string.lowe r(md5sum(f_md5) ))
print str(string.lowe r(md5sum(f_md5) ) == string.lower(in fo_res[2]))

and the output are

01b7ebfc27437a9 0cc421c50df8f9a c5
01b7ebfc27437a9 0cc421c50df8f9a c5
32
32
False

I was wondering why the last print statement is returning false when two
strings are identical?

Senthoor

_______________ _______________ _______________ _______________ _____
Tired of spam? Get advanced junk mail protection with MSN 8.
http://join.msn.com/?page=features/junkmail

Jul 18 '05 #1
2 2563
Senthoorkumaran Punniamoorthy wrote:
I am printing these information.

print string.lower(in fo_res[2])
print string.lower(md 5sum(f_md5))
print len(string.lowe r(info_res[2]))
print len(string.lowe r(md5sum(f_md5) ))
print str(string.lowe r(md5sum(f_md5) ) == string.lower(in fo_res[2]))

and the output are

01b7ebfc27437a9 0cc421c50df8f9a c5
01b7ebfc27437a9 0cc421c50df8f9a c5
32
32
False

I was wondering why the last print statement is returning false when two
strings are identical?

Senthoor

_______________ _______________ _______________ _______________ _____
Tired of spam? Get advanced junk mail protection with MSN 8.
http://join.msn.com/?page=features/junkmail
import urllib2
import sre
import string
import sys
import md5
import socket
import logging
import getopt
import os
from property import property

md5_bufsize=809 6
bufsize=8096
'''
Change History
--------------
1.01g:
i. file close from file_writer() removed so that caller can close the file
ii. exception handling introduced for mail sending to handle missing
SMTP config
iii.file_Dled() method is replaced
iv. The program doesn't exit if it can't find the logfile anymore. It
just downloads again.
v. small bug fixes
vi. grab_info was made little less complicated by removing the
compilation of regex

1.01h:
i. If the MD5 check sum doesn't match, trying n number of times
'''
version="1.01h"

# MD5 checksum program taken from python_home/tools/scripts/md5sum.py
# That was a stand alone script with many options
# Just took the function which did the checksumming, and reduced it.

def md5sum(fp):
m = md5.new()
try:
while 1:
data = fp.read(md5_buf size)
if not data:
break
m.update(data)
except IOError, msg:
log.error('I/O error: '+ str(msg))
log.error('Syst em Abort')
sys.exit(1)

return m.hexdigest()

'''Reads the file from fp_in and writes it to fp_out. fp_in normally is
the file being
downloaded and fp_out is the file being written to the local disk'''
def file_writer(fp_ in, fp_out):
try:
log.info('File Downloading in Progress.',)
while 1:
data = fp_in.read(bufs ize)
if not data:
break
fp_out.write(da ta)
fp_out.flush()
#fp_out.write(' senthoor')
#fp_out.flush()
except IOError, msg:
log.error('Erro r resolving address: '+ str(msg))
log.error('Syst em Abort')
sys.exit(1)
except socket.error, msg:
log.error('Soke t error: '+ str(msg))
log.error('Syst em Abort')
sys.exit(1)

def send_mail(mails erver,from_addr , to_addr, file_name):
msg = 'Greetings all, \n The lastest virus definition file' +
file_name + ' has been down loaded'
server = smtplib.SMTP(ma ilserver)
server.set_debu glevel(1)
server.sendmail (from_addr, to_addr, msg)
server.quit()

'''Takes a list of regular expressions and a Source(String) and searchs
source for
match and returns a list with all the matches'''
def grab_info(listR egEx,source):
#this needs improvement. The compilation is unnecessary and will be
removed
return map(lambda x:x.group(1),ma p(lambda x: sre.search(x,
source),listReg Ex))

def show_usage():
print 'under construnction'

'''Processes the command line argument'''
def process_args(a) :
try:
args = getopt.getopt(a[1:],'dv')
for x in args[0]:
if x[0] == '-d':
log.setLevel(lo gging.DEBUG)
if x[0] == '-v':
print 'theRetriever '+ version +', MotleyPythons'
sys.exit(0)
except getopt.GetoptEr ror,msg:
show_usage()
sys.exit(1)

'''Checks the log file whether the file name exsits. If the file name
exsits then no need to download the file since its been already
downloaded'''
def file_Dled(file, fileName):
if os.path.exists( file):
return sre.search(file Name,open(file) .read())

'''When the file is downloaded and written to the local disk the
log file updated with the file name'''
def file_DlOK(file, fileName):
exc = 0
try:
fp = open(file,'a')
fp.write(fileNa me + '\n')
fp.close
except IOError,msg:
log.error('I/O error: '+ str(msg))
log.error('Syst em Abort')
sys.exit(1)

#Logging Initialised
logging.basicCo nfig()
log = logging.getLogg er('Retriever')
log.setLevel(lo gging.INFO)
process_args(sy s.argv)
# Get information from config file
config = property('confi g.cfg')
log.debug('Conf ig Loaded')
dllog=config.ge t_safe('LOCATIO N','')+'dledfil e.lst'
no_of_trys = 0

#this is being introduced so that file be downloaded if the it was
#not download failed and we are going to have a time testing this:-)
md5_error=1 #at the begining no file so md5_error is true:-)
log.debug('Retr ies :' + str(config.get_ safe('RETRIES', 0)))
while md5_error and (no_of_trys<=in t(config.get_sa fe('RETRIES',0) )):
no_of_trys +=1

#until its proven md5 mismatch exit we assume it doesn't
#this helps us only to repeat downloaing in the case of mismatch
#and if the downloading stops for other reasons
md5_error = 0
try:
f1 = urllib2.urlopen (config.get('UR L'))
log.debug(confi g.get('URL') + 'has been read')
except urllib2.URLErro r, msg:
log.error('Erro r Reading ' + config.get('URL ') + '\n' + str(msg))
log.error('Syst em Abort')
sys.exit(1)
htmlsource = f1.read()
f1.close()

info_regex =
['href="(.*2\d{7 }-\d{3}-i32.exe)"','hre f=".*(2\d{7}-\d{3}-i32.exe)"','MD5 </a>:\s(.*)\s<a']

info_res = grab_info(info_ regex,htmlsourc e)
log.debug('retr ieved info \n' + str(info_res))
# Exit if file already loaded
if file_Dled(dllog ,info_res[1]):
log.info('File already downloaded. Process Stopping',)
sys.exit(0)

#reading and writing to a local file
virusdeflocal=o pen(config.get_ safe('LOCATION' ,'')+info_res[1],'wb')
authinfo = urllib2.Request (config.get('UR L'))
virusdefserver =
urllib2.urlopen ('http://'+authinfo.get_ host()+info_res[0])
file_writer(vir usdefserver,vir usdeflocal)
virusdeflocal.c lose()
virusdefserver. close()

f_md5=open(conf ig.get_safe('LO CATION','')+inf o_res[1],'rb')
if string.lower(md 5sum(f_md5)) == string.lower(in fo_res[2]):
log.debug("Yipe e !!!, it works!!")
# Have to copy the file to the common share
# Must have location in config file

# Put entry in logfile
file_DlOK(dllog ,info_res[1])
try:

send_mail(confi g.get('SMTP'),c onfig.get('FROM _ADDR'),config. get('TO_ADDR'), filename)

except KeyError, msg:
log.error('Mail not sent: ' + str(msg))

else:
log.debug("Bumm er")
md5_error=1

Senthoorkumaran Punniamoorthy,
s1='01b7ebfc274 37a90cc421c50df 8f9ac5'
s2=s1
import string
print str(string.lowe r(s1))==string. lower(s2)

True

??????????????? ?????????/
wes

Jul 18 '05 #2
>>>>> "Senthoorkumara n Punniamoorthy" <so***********@ hotmail.com> (SP) wrote:

SP> I am printing these information.
SP> print string.lower(in fo_res[2])
SP> print string.lower(md 5sum(f_md5))
SP> print len(string.lowe r(info_res[2]))
SP> print len(string.lowe r(md5sum(f_md5) ))
SP> print str(string.lowe r(md5sum(f_md5) ) == string.lower(in fo_res[2]))

SP> and the output are

SP> 01b7ebfc27437a9 0cc421c50df8f9a c5
SP> 01b7ebfc27437a9 0cc421c50df8f9a c5
SP> 32
SP> 32
SP> False

SP> I was wondering why the last print statement is returning false when two
SP> strings are identical?

They are not identical, because md5sum is reading from the file.
--
Piet van Oostrum <pi**@cs.uu.n l>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.***********@h ccnet.nl
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2541
by: Neil Zanella | last post by:
Hello, Consider the following program. There are two C style string stack variables and one C style string heap variable. The compiler may or may not optimize the space taken up by the two stack variables by placing them at the same address (my g++ compiler does this). Therefore the output of the given C program is compiler dependent. What is worse, the program does not do what its writer most likely intended, since, std::set's find()...
51
8268
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct code? many thx!
46
5137
by: yadurajj | last post by:
Hello i am newbie trying to learn C..I need to know about string comparisons in C, without using a library function,...recently I was asked this in an interview..I can write a small program but I was told that wouldn't it be wise to first get the length of the strings..if it doesn't match then they are not the same..I agreed...then he said..but again that would be an overhead first measuring the length...and then doing a character by...
4
2268
by: Dim | last post by:
I found that C# has some buggy ways to process string across methods. I have a class with on global string var and a method where i add / remove from this string Consider it a buffer... with some values and separators class { private string globalvar = ""; private void manipulate (whattodo ) //substring, join, etc....
19
9514
by: David zhu | last post by:
I've got different result when comparing two strings using "==" and string.Compare(). The two strings seems to have same value "1202002" in the quick watch, and both have the same length 7 which I have tried to print out by debug.writeline(). But the "==" operator results false, and string.Compare() results true. Somebody helps me!
5
14908
by: BILL | last post by:
Hi Everyone, I've been looking through these .NET groups and can't find the exact answer I want, so I'm asking. Can someone let me know the best way (you feel) to search a C# string for an occurance of a CASE INSENSITIVE substring, returning the found position. I'm speaking of larger strings to search as well ~50K-500K. Here's what I have so far:
5
657
by: MaSTeR | last post by:
Can anyone provide a practical short example of why in C# I shouldn't compare two strings with == ? If I write this in JAVA String string1 = "Widget"; if (string1 == "Widget") System.Console.WriteLine("String1 Equal.");
26
3807
by: Neville Lang | last post by:
Hi all, I am having a memory blank at the moment. I have been writing in C# for a number of years and now need to do something in VB.NET, so forgive me such a primitive question. In C#, I test whether a string has a value or not by the following syntax: if (thisString.Trim() == "") {
12
2481
by: ujjc001 | last post by:
Here's one for ya. I want to create a relational operator from a string object, i.e. I want to somehow be able to say: string opString = ">="; int i1 = "20"; int i2 = "10"; if (i1 somemethodhere(opString) i2) { //do the true here } else {
6
4342
by: aznimah | last post by:
hi, i'm work on image comparison. i'm using the similarity measurement which i need to: 1) convert the image into the binary form since the algorithm that i've use works with binary data for the computation 2) compare the string binary data to get the similarity or dissimilarity result. The problem is, i already done with the image (jpg) conversion to binary and also try the algorithm structure in C# language, but i having a problem to...
0
8728
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8926
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7813
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6563
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5903
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4404
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3092
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2392
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2030
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.