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))
AndyG
  • 39,700
  • 8
  • 109
  • 143
Karthik S
  • 847
  • 1
  • 8
  • 22
  • 1
    The search on Stackoverflow *does* work: http://stackoverflow.com/search?tab=relevance&q=typeerror%3a%20%27str%27%20does%20not%20support%20the%20buffer%20interface – Lennart Regebro Jan 30 '12 at 11:14
  • 1
    exact duplicate of [TypeError: 'str' does not support the buffer interface](http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface) And two million other questions with the exact same error message and answer. – Lennart Regebro Jan 30 '12 at 11:16

1 Answers1

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.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251