2

Check out the bytes-to-bytes and string-to-string encodings in Python 3:

http://docs.python.org/3/library/codecs.html#standard-encodings (Search for bytes-to-bytes)

How do I use these? I've tried using them in .encode and .decode but it didn't work.

1 Answer 1

1

Accessing them through the codecs module by a non-alias name seems to work, in Python 3.2 and above:

>>> import codecs
>>> codecs.decode(b"asdf", "base64_codec")
b'j\xc7_'
>>> codecs.encode(b"asdf", "base64_codec")
b'YXNkZg==\n'
>>> 

Using an alias name ("base64"), Python < 3.2, or bytes.decode all seem to fail.

Sign up to request clarification or add additional context in comments.

4 Comments

Is this really the shortest way? That kinda sucks.
@RamRachum Semantically, in Python 3, encode and decode are use specifically in respect to unicode, which is why bytes doesn't have encode, and str doesn't have decode. While it's less convenient than Python 2, it does separate going to and from unicode from other forms of text / byte manipulation.
@RamRachum: How does this in any universe "kinda suck"? That code is clear, readable, pretty obvious and not particularly long?
In this very universe where a language called Python 2.x exists. Whether you say this sucks depends on what you compare it to. I'm sure that there are some languages that if you'd compare it to, you'd think it's not particularly long. But if you compare it to Python 2, it's about TWICE as long.

Your Answer

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.