Reputation: 4926
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
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
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