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") 
Sede
61.5k20 gold badges159 silver badges162 bronze badges
asked Jul 29, 2015 at 23:55

1 Answer 1

8

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()
answered Jul 30, 2015 at 0:10
Sign up to request clarification or add additional context in comments.

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.