[Python] How do I read a string as if it were bytes

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    I have a string in a file encoded in utf-8. It contains escape sequences that should not be interpreted as Unicode code points, but rather as binary numbers. How can I convert it to bytes?

    For example, consider the string 'abc \x00\x01\xff'. If I were to type this in to the Python interpreter as a bytes literal I would get:

    >>> b = b'abc \x00\x01\xff'
    >>> list(b)
    [97, 98, 99, 32, 0, 1, 255]


    But if if I start with a string and try to interpret the escape sequences I get:

    >>> s = r'abc \x00\x01\xff'.encode('utf8').decode('unicode-escape')
    >>> list(s)
    ['a', 'b', 'c', ' ', '\x00', '\x01', 'ÿ']


    Notice that \xff is not interpreted as a binary number, it is taken to be a Unicode code point. What I need is a 'binary-escape'.

    How can I read the string from the file and interpret it as if I entered it as a bytes literal?

    Continue reading...

Compartilhe esta Página