Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add "b" prefix to python variable?

Adding the prefix "b" to a string converts it to bytes:

b'example' 

But I can't figure out how to do this with a variable. Assuming string = 'example', none of these seem to work:

b(string) b string b'' + string 

Is there a simple way to do this?

like image 454
zombio Avatar asked Oct 22 '13 07:10

zombio


People also ask

How do you add b in Python?

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. Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256.

What is b prefix in Python?

A prefix of 'b' or 'B' is ignored in Python 2. In Python 3, 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.

What does b mean in front of string Python?

The b" notation is used to specify a bytes string in Python. Compared to the regular strings, which have ASCII characters, the bytes string is an array of byte variables where each hexadecimal element has a value between 0 and 255.


1 Answers

# 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.

like image 55
Leonardo.Z Avatar answered Sep 18 '22 07:09

Leonardo.Z