在Python 3中压缩/解压缩字符串

时间:2020-10-01 16:49:44

标签: python gzip zlib

此问题已多次解决herehere,但并未完全回答。由于解压缩不会产生原始字符串。

>>> s = "some string to test zlib"
>>> z = zlib.compress(s)
Traceback (most recent call last):
   File "<input>", line 1, in <module>
   TypeError: a bytes-like object is required, not 'str'
>>> z = zlib.compress(s.encode("utf8"))
>>> y = zlib.decompress(z)
>>> y
b'some string to test zlib'
>>> print (s, y)
some string to test zlib b'some string to test zlib'

因此,解压缩将返回包含在“ b”中的原始字符串。

>>> p = str(y)
>>> p
"b'some string to test zlib'"

与gzip相同的行为。

1 个答案:

答案 0 :(得分:1)

bytes-b只是表明这是正在打印的s = "some string to test zlib" z = zlib.compress(s.encode("utf-8")) y = zlib.decompress(z) y print (s, y) print (s, y.decode('utf-8')) 类型:

some string to test zlib b'some string to test zlib'
some string to test zlib some string to test zlib

输出:

function randChar(length) {
  var result = '';
  var characters = 'xyz123ABC';
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}


var $btn = $("#btn");
var $con = $("#con");
$btn.click(function() {
  var $i;
  for ($i = 0; $i < 10; $i++) {
    var $theni = randChar(64);
  }
  $con.html($theni);
});