0

I receive a row of bytes over a socket connection as data. When I print(data) it tells me

b'123' 

How can I convert it back to a string and only print 123? If I do type(data) it puts out

<class 'bytes'>

When I do data.decode("utf-8") it puts me out 'bytes' object has no attribute 'decode'. Do I mix something up with the type?

Thanks

  • Yes, you must be mixing up two different `data` objects. The one you examined with `print(data)` and `type(data)` is a `bytes` object and it will have a `.decode()` method. If the error is `'str' object has no attribute 'decode'` then you are dealing with a different `data`, one that is (evidently) a `str` object rather than a `bytes` object. – jez Jan 15 '16 at 16:58
  • So why does it show me after I print(type(data)). Is it a mistake by python3? Should it be ? – user5526679 Jan 15 '16 at 17:02
  • I'm saying try it again. Recreate `data` from scratch, examine its type, and then look for its `decode` method. Previously, you must have changed `data` without realizing it, in between those two actions. Over and out. – jez Jan 15 '16 at 17:03
  • Sorry I wrote it wrong above. After print(data.encode('utf-8')) it says AttributeError: 'bytes' object has no attribute 'encode' – user5526679 Jan 15 '16 at 17:06
  • datax = str(b"xxx") #string print (datax) also prints out b'xxx' This is wrong? Why is that? – user5526679 Jan 15 '16 at 17:17
  • I dont get it in python3datax = str(b"xxx") print (datax) puts out b'xxx' whyy????? – user5526679 Jan 15 '16 at 17:35
  • Ah, that's a different confusion but easier to straighten out. `bytes` objects have a decode method but not encode; `str` objects, vice versa. That's because it's an asymmetric system: you "decode" a `bytes` object into a `str`, and conversely "encode" a `str` object into a `bytes`. `str(x)` is no longer the approved way to convert a `bytes` object `x` to `str` - it just gives you some sort of printable representation, in this case (IMO stupidly) the same as `repr(b)`. The powers that be want to force you to use `.decode` explicitly. – jez Jan 15 '16 at 17:38
  • data.decode("uft-8") does not work as well. Why is it so difficult to convert this stuff. Do I need a regex to cut b"*" out or what... come on python3 – user5526679 Jan 15 '16 at 17:50
  • AttributeError: 'str' object has no attribute 'decode'. – user5526679 Jan 15 '16 at 17:51
  • ok SOLUTION http://stackoverflow.com/questions/17013089/python-get-rid-of-bytes-b – user5526679 Jan 15 '16 at 18:01
  • print (str(datax[2:-1])) – user5526679 Jan 15 '16 at 18:02
  • datawithoutb = str(data)[2:-1] print(datawithoutb) – user5526679 Jan 15 '16 at 18:13

0 Answers0