exAres
exAres

Reputation: 4926

How to make update function of hashlib md5 work in both Python 2 and Python 3?

I want to create a hash of string_variable.

In Python2:

def get_hash_python2(string_variable):
  import hashlib
  m = hashlib.md5()
  m.update(string_variable) # this takes string as argument
  return m.digest()

In Python3:

def get_hash_python3(string_as_bytes)
  import hashlib
  m = hashlib.md5()
  m.update(string_as_bytes) # this takes bytes as argument
  return m.digest()

How to write a single get_hash function to get hash for the string_variable that would be compatible with both Python2 and Python3?

Upvotes: 1

Views: 1990

Answers (3)

Sunitha
Sunitha

Reputation: 12015

Use str.encode to convert the string variable to the appropriate form acceptable by hashlib

Both on Python2 and Python3

import hashlib

def get_hash(string_variable):
    m = hashlib.md5()
    m.update(string_variable.encode())
    return m.digest()

Upvotes: 1

Skaperen
Skaperen

Reputation: 463

Back when I wrote code to run in either Python2 or Python3 I would often have both a Python2 version and a different Python3 version, in an if that checked which version. I would usually cheat on the version test like:

if bytes == str:
    def my_function():
        ...
        # Python2 version of code goes here.
        ...
else:
    def my_function():
        ...
        # Python3 version of code goes here.
        ...

This version test only works in version 2.6 and 2.7 of Python2.

To convert a string that only has values in it that are numerically from 0 to 255, you can do this:

bytes_var = bytes(ord(x) for x in str_var)

This only works in Python3. By changing bytes to bytearray it works in both Python2 and Python3.

Upvotes: 0

Virtual Dreamer
Virtual Dreamer

Reputation: 43

In python3 if i am not wrong

m.update(b"string_as_bytes")

Upvotes: 0

Related Questions