Add "b" prefix to python variable?
# only an example, you can choose a different encoding
bytes('example', encoding='utf-8')
In Python3:
Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
In Python2:
A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3.
More about bytes():
bytes([source[, encoding[, errors]]])
Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.
Accordingly, constructor arguments are interpreted as for bytearray().
Bytes objects can also be created with literals, see String and Bytes literals.
Use bytes()
:
>>> bytes("hello", encoding="ascii")
b'hello'
string = bytes(string, encoding= 'utf-8')
where 'string' is your variable.
Or use the bytes.decode()
method to convert to string
(using a given encoding):
>>> b'hello'.decode('utf-8')
'hello'
The opposite conversion is str.encode()
to convert a string
to bytes
:
>>> 'hello'.encode('utf-8')
b'hello'