Last active
March 12, 2022 10:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gzip.compress()
exists too since 3.2. This whole gist is now unnecessary, except for 3.0 and 3.1. (Except thatgzip.decompress()
doesn't exist in 3.0 and 3.1 either so the first commit of this gist is needed there.)