Peaser
Peaser

Reputation: 575

Strings listed as different by python even though they are clearly the same?

I have 2 strings: str1 and str2.

How I got str1:

class Verifier(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self, show='*')
        self.button = tk.Button(self, text="Verify", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        p = self.entry.get()
        str1 = hashlib.md5(p).hexdigest()

Str1 is the md5 of text entered into a tkinter text box.

If I enter 'hello', Str1 is '5d41402abc4b2a76b9719d911017c592'

How I got Str2:

Str2 = open("x.txt", "r").readlines()[0]

This is a text file with the md5 hash of 'hello' (5d41402abc4b2a76b9719d911017c592).

Here is a script that describes this:

import Tkinter as tk, hashlib
Str2 = open("x.txt", "r").readlines()[0]
class Verifier(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self, show='*')
        self.button = tk.Button(self, text="Verify", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        p = self.entry.get()
        Str1 = hashlib.md5(p).hexdigest()
        print Str1
        print Str2 #Notice how these are the same
        print Str1 == Str2 #Why does this return false
        print str(Str1) == str(Str2) #FOR GOOD MEASURE
Verifier().mainloop()

I don't know if it's just me, or what. I am running python 2.7

Here is a screenshot : screenshot

Please help.

Upvotes: 0

Views: 57

Answers (1)

confused_at_times
confused_at_times

Reputation: 545

Str2 has a newline character at the end. Do:

Str2.strip()

To remove it.

EDIT: As mentioned in a comment, str.rstrip() will strip characters to the right of the string only, whereas str.strip() strips from both ends. Feel free to use either, however, beware of strings that have a blank space at the start when parsing in from file, as str.rstrip() will not remove it. This is the main reason why I just stick with str.strip() by default. I wouldn't concern myself with efficiency here either; I can pretty much guarantee profiling most codes will find bigger bottlenecks than the difference between str.strip() and str.rstrip().

Upvotes: 2

Related Questions