0

I'm working on a project which saves some bytes as a string, but I can't seem to figure out how to get the bytes back to a actual bytes!

I've got this string:

"b'\x80\x03]q\x00(X\r\x00\x00\x00My First Noteq\x01X\x0e\x00\x00\x00My Second Noteq\x02e.'"

As you can see, the type() function on the data returns a string instead of bytes:

<class 'str'>

How can I convert this string back to bytes?

Any help is appreciated, Thanks!

CodeShady
  • 7
  • 4
  • 1
    Does this answer your question? [string encoding and decoding?](https://stackoverflow.com/questions/11339955/string-encoding-and-decoding) – OneCricketeer Feb 21 '20 at 14:27
  • Unfortunately, No. – CodeShady Feb 21 '20 at 14:39
  • Why not? You need to encode the string – OneCricketeer Feb 21 '20 at 14:50
  • 1
    If I encode the string, id just get a DOUBLE encoded string! Like this: b"b'..... – CodeShady Feb 21 '20 at 15:07
  • Seems like you actually have a string, then. And not bytes. Please show a [mcve] of how you get your data – OneCricketeer Feb 21 '20 at 15:19
  • Yes, exactly! That's what it says in the post. I've already done tons of testing on my code to try and get it working. I can't seem to get it! – CodeShady Feb 22 '20 at 02:09
  • Again, edit the question to show how you **got** this data – OneCricketeer Feb 22 '20 at 07:20
  • I'm not sure you understand my question. (I've updated my question). The data is stored inside a variable. I just need to convert the string back to bytes without "double-byting" it. – CodeShady Feb 22 '20 at 14:39
  • @CodeShady - check my answer, you just need to drop redundant characters from your string – Grzegorz Skibinski Feb 22 '20 at 15:03
  • And how did it get into the variable to begin with? Looks like you've literally typed out `"b'\x80`, which is clearly a string, then assigned that to a variable? Why would you do that if you really wanted bytes? My point is that if this variable actually came from some other library or function, this would be solved there, not later on in your code – OneCricketeer Feb 22 '20 at 16:49

2 Answers2

0

in python 3:

>>> a=b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>> b = list(a)
>>> b
[0, 0, 0, 0, 7, 128, 0, 3]
>>> c = bytes(b)
>>> c
b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>>
Paolo Mossini
  • 1,064
  • 2
  • 15
  • 23
0

Try:

x="b'\x80\x03]q\x00(X\r\x00\x00\x00My First Noteq\x01X\x0e\x00\x00\x00My Second Noteq\x02e.'"

y=x[2:-1].encode("utf-8")

>>> print(y)

b'\xc2\x80\x03]q\x00(X\r\x00\x00\x00My First Noteq\x01X\x0e\x00\x00\x00My Second Noteq\x02e.'

>>> print(type(y))

<class 'bytes'>

You have just bytes converted to regular string without encoding - so you have redundant tags indicating that: b'...' - you just need to drop them and python will do the rest for you ;)

Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34