String to bytes in both Python 2 and 3
You can check the version using sys.version_info:
if sys.version_info < (3, 0):
data = bytes(data)
else:
data = bytes(data, 'utf8')
It is more pythonic than relying on exceptions.
This works with both version. i.e. python 2 and python 3
data = bytes(str(data).encode("utf-8"))
If you're using the six py2/3 compatibility library, you may prefer:
import six
data = bytes(data) if six.PY2 else bytes(data, 'utf8')