0

I'm importing zlib in my Python program. It works fine in Python 2.6 but shows an error when I try to run it in Python 3.2.

This is my code:

import zlib
s = 'sam'
print ("Your string length is",len(s))
t = zlib.compress(s)
print ("Your compressed string is",t)
print ("Your compressed string length is",len(t))
print ("Your decompressed string is",zlib.decompress(t))
print ("Crc32 is",zlib.crc32(t))

The error I get is this:

Your string length is 3
Traceback (most recent call last):
  File "F:\workspace\samples\python\zip.py", line 4, in <module>
    t = zlib.compress(s)
TypeError: 'str' does not support the buffer interface

But the above program works fine in Python 2.6. Should I use an alternative to zlib? Please help me.

Edit: I got it to work. It seems I needed to encode it. Here is the revised code:

import zlib
s = 'sam'
print ("Your string length is",len(s))
s=s.encode('utf-8')
t = zlib.compress(s)
print ("Your compressed string is",t)
print ("Your compressed string length is",len(t))
print ("Your decompressed string is",zlib.decompress(t))
print ("Crc32 is",zlib.crc32(t))
2

1 Answer 1

4

Th str type in Python is no longer a sequence of 8-bit characters, but a sequence of Uncode characters. You need to use the bytes type for binary data. You convert between strings and bytes by encoding/decoding.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.