0

Say, I've a byte string, e.g.:

bs: bytes = b'\xaf]\x95Q\x0b'

Now, take out the string part by copy and paste and assign it to a string variable:

s: string = "\xaf]\x95Q\x0b"

How do I convert s, say with a function cnv(s: str) -> bytes, back to bytes so the expression bs == cnv(s) evaluates to True?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
nanitous
  • 681
  • 7
  • 17
  • [`bs.decode()`](https://docs.python.org/3/library/stdtypes.html#bytes.decode) and [`s.encode()`](https://docs.python.org/3/library/stdtypes.html#str.encode). – Olvin Roght May 02 '22 at 09:36
  • @OlvinRoght please post it as an answer, don't asnwer in comments – FlyingTeller May 02 '22 at 09:38
  • @FlyingTeller, it doesn't deserve to be an answer as this question is obviously a duplicate and will be closed soon. – Olvin Roght May 02 '22 at 09:39
  • _"take out the string part by copy and paste and assign it to a string variable"_ - why? – jonrsharpe May 02 '22 at 09:41
  • @jonsharpe, this was the shortest way to set up the question. Explaining why would need to describe the whole situation which would run counter to the rules of SO for asking questions: "keep it consise". – nanitous May 02 '22 at 10:19
  • As far as I can tell the only place "concise" appears in the [help] is in https://stackoverflow.com/help/privileges/approve-tag-wiki-edits. [Ask] suggests you _"Explain how you encountered the problem you're trying to solve"_, which helps avoid [XY problems](https://meta.stackexchange.com/q/66377/248731). – jonrsharpe May 02 '22 at 10:25
  • @jonsharpe, If you insist. A customer uses these to communicate bytes over a serial line. C'est tout. – nanitous May 02 '22 at 10:27
  • @OlvinRoght Yes, I surmised that much. But it was beyond me which codec to use. So, your answer wasn't that useful to me. Because I couldn't find the appropriate codec, I was under the impression that some other _pythonic_ way would exists, and therefore I decided to post the question. – nanitous May 02 '22 at 10:29
  • Don't put answers in the question, [self-answered question](https://stackoverflow.com/help/self-answer) must still be a question and answer pair. If you edit the question to clarify where it departs from the current dupe ("Edit:" isn't needed, we can all see the history) it can be reviewed for reopening. How you _actually get `s`_ is useful context to include. – jonrsharpe May 02 '22 at 11:05

0 Answers0