-4

I want to convert a string

'hello world'

to

b'hello world'

in python, how can I do that?

  • Variable.encode() to form a bytes string and variable.decode('utf-8') to convert bytes to string – Surya Tej Aug 01 '18 at 05:36
  • Possible duplicate of [Best way to convert string to bytes in Python 3?](https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3) – Graham Aug 01 '18 at 05:44

3 Answers3

3

You can use the str.encode() method to convert a string to bytes.

>>> 'hello world'.encode()
b'hello world'
>>>

Please refer to: https://docs.python.org/3/library/stdtypes.html#str.encode

blhsing
  • 91,368
  • 6
  • 71
  • 106
0

You can use b = bytes(mystring, 'utf-8') notation to turn your string into bytes object. But there are many similar questions and related answers in stackoverflow to your question. You should have searched for your question first.

ozata
  • 542
  • 1
  • 5
  • 16
-1
>>> """b'hello world'"""
b'hello world'
kkblue
  • 183
  • 10