How can I decode a utf-8 byte array to a string in Python2?
Question: I have an array of bytes representing a utf-8 encoded string. I want to decode
these bytes back into the string in Pyton2. I am relying on Python2 for my
overall program, so I can not switch to Python3.

    
    
    array = [67, 97, 102, **-61, -87**, 32, 70, 108, 111, 114, 97] 
    

-> Caf**é** Flora

Since every character in the string I want is not necessarily represented by
exactly 1 byte in the array, I can not use a solution like:

    
    
    "".join(map(chr, array))
    

I tried to create a function that would step through the array, and whenever
it encounters a number not in the range 0-127 (ASCII), create a new 16 bit
int, shift the current bits over 8 to the left, and then add the following
byte using a bitwise OR. Finally it would use unichr() to decode it.

    
    
    result = []
    
    
    for i in range(len(byte_array)):
        x = byte_array[i]
        if x < 0:
            b16 = x & 0xFFFF # 16 bit
            b16 = b16 << 8
            b16 = b16 | byte_array[i+1]
            result.append(unichr(m16))
        else:
            result.append(chr(x))
    
    return "".join(result)
    

However, this was unsuccessful.

The following article explains the issue very well, and includes a nodeJS
solution:

<http://ixti.net/development/node.js/2011/10/26/get-utf-8-string-from-array-
of-bytes-in-node-js.html>


Answer: Use the little-used [`array`
module](https://docs.python.org/2/library/array.html) to convert your input to
a bytestring and then `decode` it with the UTF-8 codec:

    
    
    import array
    decoded = array.array('b', your_input).tostring().decode('utf-8')
    

