Skip to content

Instantly share code, notes, and snippets.

@Garrett-R
Last active March 12, 2022 10:17
Show Gist options
  • Save Garrett-R/dc6f08fc1eab63f94d2cbb89cb61c33d to your computer and use it in GitHub Desktop.
Save Garrett-R/dc6f08fc1eab63f94d2cbb89cb61c33d to your computer and use it in GitHub Desktop.
Demo of how to gzip and gunzip a string in Python 3
"""How to gzip a string.
This works for Python 3.2. For 3.1-, look at the original gist (under "Revisions")
"""
import gzip
def gzip_str(string_: str) -> bytes:
return gzip.compress(string_.encode())
def gunzip_bytes_obj(bytes_obj: bytes) -> str:
return gzip.decompress(bytes_obj).decode()
string_ = 'hello there!'
gzipped_bytes = gzip_str(string_)
original_string = gunzip_bytes_obj(gzipped_bytes)
assert string_ == original_string
@Garrett-R
Copy link
Author

Great point @jack980517, I've updated it to reflect that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment