The official node.js documentation for Buffer is the best place to check for something like this. As previously noted, Buffer currently supports these encodings: 'ascii', 'utf8', 'utf16le'/'ucs2', 'base64', 'base64url', 'latin1'/'binary', and 'hex'.

Answer from mscdex on Stack Overflow
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ codecs
codecs โ€“ String encoding and decoding - Python Module of the Week
Now available for Python 3! Buy the book! ... The codecs module provides stream and file interfaces for transcoding data in your program. It is most commonly used to work with Unicode text, but other encodings are also available for other purposes. CPython 2.x supports two types of strings for working with text data.
Top answer
1 of 2
3

The most concise I could come up with is the following, which you may be able to make more concise with a few convenience functions (or even replacing/overriding the print function):

# -*- coding=utf-8 -*-
import codecs
import os
import sys

# if you include the -*- coding line, you can use this
output = 'bar' + u'โ†’'
# otherwise, use this
output = 'bar' + b'\xe2\x86\x92'.decode('utf-8')

if sys.stdout.encoding == 'UTF-8':
    print(output)
else:
    output += os.linesep
    if sys.version_info[0] >= 3:
        sys.stdout.buffer.write(bytes(output.encode('utf-8')))
    else:
        codecs.getwriter('utf-8')(sys.stdout).write(output)

The best option is using the -*- encoding line, which allows you to use the actual character in the file. But if for some reason, you can't use the encoding line, it's still possible to accomplish without it.

This (both with and without the encoding line) works on Linux (Arch) with python 2.7.7 and 3.4.1. It also works if the terminal's encoding is not UTF-8. (On Arch Linux, I just change the encoding by using a different LANG environment variable.)

LANG=zh_CN python test.py

It also sort of works on Windows, which I tried with 2.6, 2.7, 3.3, and 3.4. By sort of, I mean I could get the 'โ†’' character to display only on a mintty terminal. On a cmd terminal, that character would display as 'ฮ“รฅร†'. (There may be something simple I'm missing there.)

2 of 2
1

If you don't need to print to sys.stdout.buffer, then the following should print fine to sys.stdout. I tried it in both Python 2.7 and 3.4, and it seemed to work fine:

# -*- coding=utf-8 -*-
print("bar" + u"โ†’")
๐ŸŒ
W3Schools
w3schools.com โ€บ nodejs โ€บ met_buffer_tostring.asp
Node.js buffer toString() Method
The toString() method returns the buffer object according to the specified encoding. ... Coding fundamentals as bite-sized lessons and challenges. ... If you want to use W3Schools services as an educational institution, team or enterprise, send ...
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ codecs.html
codecs โ€” Codec registry and base classes
If the replacement is bytes, the encoder will simply copy them into the output buffer. If the replacement is a string, the encoder will encode the replacement. Encoding continues on original input at the specified position.
๐ŸŒ
Bun
bun.sh โ€บ binary data โ€บ convert a buffer to a string
Convert a Buffer to a string - Bun
August 4, 2026 - The Buffer class provides a .toString() method that converts a Buffer to a string. const buf = Buffer.from("hello"); const str = buf.toString(); // => "hello" You can optionally specify an encoding and byte range. const buf = Buffer.from("hello ...
Find elsewhere
Top answer
1 of 2
2

I think struct is what you are looking for. Anyhow you have to find out the serialized data format. It is not a C/C++ struct that is sent but (hopefilly) a well described serialized format which may be binaray. Important topics are little/big endianess, size of double, size of int and padding.

from struct import *
arg1, arg2, arg3, arg4, arg5 = unpack('!ddddi', buffer)

standard sizes would require 36 bytes

>>> from struct import *
>>> a='\x00\x00\x00\x01'*9
>>> unpack('>ddddi', a)
(2.1219957915e-314, 2.1219957915e-314, 2.1219957915e-314, 2.1219957915e-314, 1)
>>> unpack('<ddddi', a)
(7.291122046717944e-304, 7.291122046717944e-304, 7.291122046717944e-304, 7.291122046717944e-304, 16777216)
>>> unpack('!ddddi', a)
(2.1219957915e-314, 2.1219957915e-314, 2.1219957915e-314, 2.1219957915e-314, 1)
>>>

EDIT: unpacking to variables, named tuple and class

unpack directly to your variables

from struct import unpack 
b = "\x00\x00\x00\x05\x00\x00\x00\x2a"

x, y = unpack('!ii', b)
print x
print y

unpack to named tuple

from struct import unpack 
from collections import namedtuple
b = "\x00\x00\x00\x05\x00\x00\x00\x2a"

Point = namedtuple('Point', 'x, y')

p = Point._make(unpack("!ii", b))
print p.x
print p.y

remember: tuple attributes are read only

unpack and initalize a class

from struct import unpack 
b = "\x00\x00\x00\x05\x00\x00\x00\x2a"

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(*unpack('!ii', b))
print p.x
print p.y
2 of 2
2

I too used struct unpacking (and had to search the character codes every time) until I learned to do the same using ctypes. I have no idea which one performs faster, but I do know which one I can translate without problems just looking at the C definition.

from ctypes import LittleEndianStructure, BigEndianStructure, c_int16, c_double, sizeof
#there are bit explicit types if you want to fix the size, like c_int8/16/32/64

class Packet(LittleEndianStructure): # replace by BigEndian as needed
    _fields_ = [
        ("arg1", c_double),
        ("arg1", c_double),
        ("arg3", c_double),
        ("arg4", c_double),
        ("arg5", c_int16)
        ]
    _pack_=1 # comment this or not depending on padding

mypacket = Packet.from_buffer_copy(payload)

It is for me much easier to read, and it has the advantage of providing me with an object that collects all the data and can be accessed by name

print(mypacket.arg1)
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-string-encode-decode
Python String Encode and Decode: Complete Guide | DigitalOcean
Master Python string encode() and decode() methods. Learn UTF-8, ASCII, Unicode handling, error handling modes, and practical encoding/decoding examples.
๐ŸŒ
Kodeclik
kodeclik.com โ€บ python-string-buffer
Python String Buffer
October 16, 2024 - Now that we have that out of the way, what is a string buffer? A string buffer in Python is an object that holds a sequence of characters, allowing us to manipulate and modify strings efficiently.
๐ŸŒ
Real Python
realpython.com โ€บ convert-python-bytes-to-strings
How to Convert Bytes to Strings in Python โ€“ Real Python
July 18, 2026 - How do you convert bytes to a string in Python?Show/Hide ยท Call .decode() on the bytes object. It returns a str, using UTF-8 by default unless you pass a different character encoding.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-bytes-to-string-how-to-convert-a-bytestring
Python Bytes to String โ€“ How to Convert a Bytestring
April 10, 2023 - In this example, we define a byte string b"Hello, world!" and use the str() constructor to convert it to a string object. We specify the encoding format as utf-8 using the encoding parameter.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ bytes-to-string-python
How to Convert Bytes to String in Python | DataCamp
June 12, 2024 - The .decode() method returns a string representing the bytes object. In this example, UTF-8 decoding is used. UTF-8 is the default encoding, so it's not required in the example above, but we can also use other encodings. Python has a built-in bytes data structure, which is an immutable sequence of integers in the range 0 to 255.
๐ŸŒ
Python Pool
pythonpool.com โ€บ home โ€บ tutorials โ€บ convert bytes to string in python with decode()
Convert Bytes to String in Python with decode()
July 13, 2026 - Decode bytes at the boundary where binary data becomes text, and make the encoding and error policy explicit. To convert bytes to a string in Python, call decode() on the bytes object and pass the correct encoding.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ io.html
io โ€” Core tools for working with streams
BufferedRandom provides a buffered interface to seekable streams. Another BufferedIOBase subclass, BytesIO, is a stream of in-memory bytes. The TextIOBase ABC extends IOBase. It deals with streams whose bytes represent text, and handles encoding and decoding to and from strings.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ encode
Python String encode()
Online Python Online JavaScript Online SQL Online Java Online HTML Online C Online C++ Online C# Online PHP Online Swift Online Kotlin Online TypeScript Online Go Online Rust Online Scala Online Dart Online R Online Ruby ... The encode() method returns an encoded version of the given string.
Top answer
1 of 5
894

If you look at the docs for bytes, it points you to bytearray:

bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.

For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.

I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself.

Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice.

2 of 5
735

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = my_str.encode()
print(type(my_str_as_bytes)) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
print(type(my_decoded_str)) # ensure it is string representation

you can verify by printing the types. Refer to output below.

<class 'bytes'>
<class 'str'>
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_encode.asp
Python String encode() Method
Remove List Duplicates Reverse ... Python Study Plan Python Interview Q&A Python Training ... The encode() method encodes the string, using the specified encoding....