If you want to produce a complete gzip-compatible binary string, with the header etc, you could use gzip.GzipFile together with StringIO:
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import StringIO # Python 3.x
import gzip
out = StringIO()
with gzip.GzipFile(fileobj=out, mode="w") as f:
f.write("This is mike number one, isn't this a lot of fun?")
out.getvalue()
# returns '\x1f\x8b\x08\x00\xbd\xbe\xe8N\x02\xff\x0b\xc9\xc8,V\x00\xa2\xdc\xcc\xecT\x85\xbc\xd2\xdc\xa4\xd4"\x85\xfc\xbcT\x1d\xa0X\x9ez\x89B\tH:Q!\'\xbfD!?M!\xad4\xcf\x1e\x00w\xd4\xea\xf41\x00\x00\x00'
Martin Thoma's answer almost worked: I had to use BytesIO as mentioned in this answer.
from io import BytesIO # Python 3.x, haven't tested 2.7
import gzip
out = BytesIO()
with gzip.GzipFile(fileobj=out, mode="w") as f:
f.write("This is mike number one, isn't this a lot of fun?")
out.getvalue()
The original code produced a TypeError: string argument expected, got 'bytes'