3 ms·
You encode strings to bytes, you decode bytes to strings. A string is an abstract representation of text, which can be encoded into whatever supported format yo
by maxbond 4y ago
You encode strings to bytes, you decode bytes to strings. A string is an abstract representation of text, which can be encoded into whatever supported format you'd like; bytes are a concrete representation of binary data, such as text encoded in UTF8, which, if it represents text, can be decoded to obtain a string.
If you think about it, that's the only way that makes sense; if you wanted to go from, say, UTF8 to UTF16, you'd need to have an intermediate step that was abstract and formatless. Similarly, when you're operating on text, you don't want it to have a particular format; the format should only exist at the edges, where you take text in and output it. The format is a way to communicate with other programs, not components within your program.
My advice would be, if that doesn't stick in your head (totally legitimate), write down a code example and stick it in a personal wiki or something. I find it really helps me to understand something once and more or less copy paste it forever.
- andrewstuart 4y agoI understand the reasons, it’s Python's fault that it’s not easy to remember and program. This is a key reason why people hated Python 3 so much IMO. For context I’m a huge advocate of Python 3, except for this (and lambda functions, but that’s another whine session).