简体   繁体   中英

How to get gzip compression as string

I need to compress a string into gzip, and get the output string like on this site: https://www.multiutil.com/text-to-gzip-compress/

示例图片(来自上面的网站)

but python's gzip module returns bytes as a compressed string.

Is it possible to convert these bytes into a string, or compress it in another way so that the output is a string?

I tried to decode in utf-8 but it gives an error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

It looks like that website is base64 encoding the output for display. I get similar (but not exactly the same) results with this code:

import gzip
import base64

teststring = "Welcome to Multiutil. This is the tool where you can compress your text or decompress your compressed value using Gzip(gz), Defalte or Brotli compression algorithms. Also you can compare the size between your source and result in bytes."

gzipped = gzip.compress(teststring.encode('utf-8'))
encoded = base64.encode(gzipped)

print(encoded.decode('utf-8'))

result:

H4sIAFSA32IC/1WPwcrCQAyEX2WOCtJ3+EXw5E3wvLZjG4gb2WR/tU/vFlEQQiATvszkRO3tSoTh
UDWkhmiH4ySOVjEtG1PcJxbiaRV9ymjErdB9EQqCj4AVDPzVPxMH/CetRHXJI/az3FbjvN5gx0vS
4MJui4XKFxHLSDpakZiu3uFP3X7cU0uzhHOZiTPjTua3q7fWEykPaJfaS5CM8zPo3QvUlCS87AAA
AA==

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM