bala bharath
bala bharath

Reputation: 63

python 3.6.3. zlib compression

I am trying to Compress a string in python 3.6.3 using zlib, but getting an error(TypeError: a bytes-like object is required, not 'str') , it was supposed to work on python 2.7- versions, here is my simple code:

import zlib
a='hellohellohelloheeloohegregrf'
b=zlib.compress(a)
print(b)

Upvotes: 3

Views: 2053

Answers (1)

Srce Cde
Srce Cde

Reputation: 1824

import zlib
a='hellohellohelloheeloohegregrf'
b=zlib.compress(a.encode("utf-8"))
print(b)

Alternative:

import zlib
a= b'hellohellohelloheeloohegregrf'
b=zlib.compress(a)
print(b)

In Python2.x this string literal is called a str object but it's stored as bytes.

In Python3.x this string literal is a str object and its type is Unicode. So, one need to prefix it with b or use .encode to get bytes object.

Upvotes: 6

Related Questions