python中的解码结果错误

时间:2017-07-20 18:19:38

标签: python

无法通过调试弄清楚,为什么我在隐藏字符串前面有b

我在结果中得到这个字符串:  '1101000011001010110110001101100011'

def retr(filename):
    img = Image.open(filename)
    binary = ''

    if img.mode in ('RGBA'):
        img = img.convert('RGBA')
        datas = img.getdata()

        for item in datas:
            digit = decode(rgb2hex(item[0], item[1], item[2]))
            if digit == None:
                pass
            else:
                binary = binary + digit
                if (binary[-16:] == '1111111111111110'):
                   # print("Success")
                    return bin2str(binary[:-16])

        return str(bin2str(binary))
    return "Incorrect Image Mode, Couldn't Retrieve"

但是控制台的结果是:b'hello'b来自哪里?

retr()之前做一些预备:

def rgb2hex(r, g, b):
    return '#{:02x}{:02x}{:02x}'.format(r, g, b)


def hex2rgb(hexcode):
     return int(hexcode[1:3], 16), int(hexcode[3:5], 16), int(hexcode[5:7], 16)


def str2bin(message):
    binary = bin(int(binascii.hexlify(message.encode("ascii")), 16))
    return binary[2:]


def bin2str(binary):
    message = binascii.unhexlify('%x' % (int('0b' + binary, 2)))
    return message

请帮助抓住b ..

3 个答案:

答案 0 :(得分:2)

x = b'hello'
print(x)
   b'hello'
print(x.decode('utf-8'))
   'hello'

我希望这显示得足以让您了解如何将其恢复为utf-8字符串

答案 1 :(得分:1)

我相信任何字节字符串都包含:" b'"字符串之前表示它来自二进制值。将二进制值转换为字符串后,可以执行替换功能:

newstring = message.replace("b", "")
newstring = message.replace("'", "")

答案 2 :(得分:1)

bin2str返回一个字节文字。您可以使用.decode()来返回字符串。

def bin2str(binary):
    message = binascii.unhexlify('%x' % (int('0b' + binary, 2)))
    return message.decode("utf-8") # or encoding of choice