Python Forum

Full Version: Zlib tutorials
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So just started playing with python, and hit a wall with zlib, just running through tutorials and came across this
 import zlib

MESSAGE = "life of brian"

compressed_message = zlib.compress(MESSAGE)
decompressed_message = zlib.decompress(compressed_message)

print "original:", repr(MESSAGE)
print "compressed message:", repr(compressed_message)
print "decompressed message:", repr(decompressed_message)
Now when I run it I get this error

Error:
pythonTest.py Traceback(mostrecentcalllast): File"Test.py",line5,in<module> compressed_message=zlib.compress(MESSAGE) TypeError:abytes-likeobjectisrequired,not'str'
I’ve tried a few different tutorials and all seem to give the same error, I’ve tried on python 2.7 and then installed 3.9 still the same
I’ve tried on a different computer too
Have I done something wrong, the tutorials done tell you to convert to binary, plus if you do it puts a “b” in front of the text, also tried ‘ instead of “ as some tutorials use that instead

Bit confused

John
Code is for Python 2 which is dead💀
If change code and run with Python 3.9.
import zlib

MESSAGE = b"life of brian"

compressed_message = zlib.compress(MESSAGE)
decompressed_message = zlib.decompress(compressed_message)

print("original:", repr(MESSAGE))
print("compressed message:", repr(compressed_message))
print("decompressed message:", repr(decompressed_message))
Output:
original: b'life of brian' compressed message: b'x\x9c\xcb\xc9LKU\xc8OSH*\xcaL\xcc\x03\x00!\x08\x04\xc2' decompressed message: b'life of brian'
So it need to be bytes in and it give bytes out.
You can easy change later if need string.
>>> decompressed_message
b'life of brian'
>>> decompressed_message.decode()
'life of brian'

# Other way around
>>> s = 'life of brian'
>>> s
'life of brian'
>>> s.encode()
b'life of brian'
(Mar-13-2021, 08:35 PM)snippsat Wrote: [ -> ]Code is for Python 2 which is dead💀
If change code and run with Python 3.9.
import zlib

MESSAGE = b"life of brian"

compressed_message = zlib.compress(MESSAGE)
decompressed_message = zlib.decompress(compressed_message)

print("original:", repr(MESSAGE))
print("compressed message:", repr(compressed_message))
print("decompressed message:", repr(decompressed_message))
Output:
original: b'life of brian' compressed message: b'x\x9c\xcb\xc9LKU\xc8OSH*\xcaL\xcc\x03\x00!\x08\x04\xc2' decompressed message: b'life of brian'
So it need to be bytes in and it give bytes out.
You can easy change later if need string.
>>> decompressed_message
b'life of brian'
>>> decompressed_message.decode()
'life of brian'

# Other way around
>>> s = 'life of brian'
>>> s
'life of brian'
>>> s.encode()
b'life of brian'
Ok, excellent, thank you very much, I’ll get rid of python 2.7 then to save confusion, and only try to find tutorials for 3.9,