6

In Python 3, bytes requires an encoding:

bytes(s, encoding="utf-8")

Is there a way to set a default encoding, so bytes always encodes in UTF-8?

The simplest way I imagine is

def bytes_utf8(s):
    return bytes(s, encoding="utf-8") 
styvane
  • 59,869
  • 19
  • 150
  • 156
qwr
  • 9,525
  • 5
  • 58
  • 102

1 Answers1

7

The documentation for bytes redirects you to the documentation for bytearray, which says in part:

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().

It looks like there's no way to provide a default.

You can use the encode method, which does have a default, given by sys.getdefaultencoding(). If you need to change the default, check out this question but be aware that the capability to do it easily was removed for good reason.

import sys
print(sys.getdefaultencoding())
s.encode()
Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622