Karthik S
Karthik S

Reputation: 857

Error when using zlib.compress function in Python 3.2

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))

Upvotes: 0

Views: 1967

Answers (1)

Lennart Regebro
Lennart Regebro

Reputation: 172219

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.

Upvotes: 4

Related Questions