Yogi Yogi - 4 months ago 10
Python Question

string mismatch in Python even if they have same value

Instead of keeping keys in my application I intent to read the keys from local file system into a variable (array of strings) and use those array elements in my oAuth APIs. However, when i used keys (in plaintext) as argument to OAuth APIs, authentication succeeds. BUT authentication failed when same value in read into a variable from file & that variable is passed to OAuth API.
Tried comparing the key value and variable value t find out they don't match though they same exactly same.

Input file looks as below:


$cat .keys
k1='jFOMZ0bI60fDAEKw53lYCj2r4'
k2='LNkyPehneIi8HeqTg1ji74H42jFkkBxZolRfzNFmaJKwLg7R7E'





secret_keys=[]

def keys_io():
key_file = open('/Users/homie/.keys', 'r+')
for key in range(1,5):
secret_keys.append(key_file.readline().split("=")[1])

print secret_keys[0]
print (secret_keys[0] == "jFOMZ0bI60fDAEKw53lYCj2r4")

keys_io()


Output:


jFOMZ0bI60fDAEKw53lYCj2r4
False


What am i missing here?

Answer

You should strip the key that you read from the file, as it has a trailing \n:

print(secret_keys[0].strip() == "jFOMZ0bI60fDAEKw53lYCj2r4")

Or do it when reading it:

for key in range(1,5):
    secret_keys.append(key_file.readline().split("=")[1].strip())
Comments