Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 860
bala bharath Avatar asked Dec 22 '25 22:12

bala bharath


1 Answers

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.

like image 91
Srce Cde Avatar answered Dec 24 '25 10:12

Srce Cde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!