78

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?

asked Oct 22, 2013 at 7:16
2
  • 2
    b converts str to bytes,not binary Commented Oct 22, 2013 at 7:19
  • whoops you're correct. Changed it. Commented Oct 22, 2013 at 7:20

5 Answers 5

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

answered Oct 22, 2013 at 7:21
Sign up to request clarification or add additional context in comments.

2 Comments

so how should you do it in python 2?
If I don't know the encoding of a string, then?
11

Use bytes():

>>> bytes("hello", encoding="ascii")
b'hello'
answered Oct 22, 2013 at 7:21

Comments

8

You can use the bytes.decode() method to convert bytes 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'
answered Mar 31, 2019 at 4:28

Comments

6
string = bytes(string, encoding= 'utf-8')

where 'string' is your variable.

answered May 31, 2018 at 5:38

Comments

0

I have checked for this for long time and i think the best way to convert a string into a varible is using vars()

vars()['variable name'] = value to assign

vars()['created_variable'] = 1
print(created_variable)
>> 1
answered Jun 12, 2019 at 13:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.