0

I'm working with some python code, and I can't seem to figure out how to get a byte representation, and a string variable to work together.

I have:

secret = b'a very secret message'

if I redefine this as:

myrealsecret = 'Hey there this is a real secret'
secret = b+myrealsecret

Why is that? and how can I get whatever value is in myrealsecret to play nicely with secret as a byte representation?

Thank you.

CodeTalk
  • 3,571
  • 16
  • 57
  • 92
  • Not a dupe........ although i do see where your going with that assumption. im asked how i can use my two variable references together. – CodeTalk Dec 22 '15 at 23:15
  • You either need to `.encode()` your string or `.decode()` your bytes, depending on whether you want the result to be bytes or str. – senshin Dec 22 '15 at 23:20
  • Well, can you explain what does *how to get a byte representation, and a string variable to work together* mean? However `b'test'+'text'` raise `TypeError` if you're using Python 3. – Remi Guan Dec 22 '15 at 23:21
  • 3
    Ah, here's the dupe: http://stackoverflow.com/q/606191/ – senshin Dec 22 '15 at 23:21
  • Im simply trying to take a variable, like myrealsecret and represent it as a byte, so that i can use it in conjunction with secret var – CodeTalk Dec 22 '15 at 23:21
  • please clarify the question. seems like you are are trying to convert string to bytes. but adding b to a string wont help. you should be seeing a NameError on the 'b'. use encode and decode methods. – rajesh.kanakabandi Dec 22 '15 at 23:22

1 Answers1

4

If you want the result to be bytes, encode the string (default encoding is utf8):

>>> secret+myrealsecret.encode()
b'a very secret messageHey there this is a real secret'

If you want the result to be a string, decode the bytes:

>>> secret.decode()+myrealsecret
'a very secret messageHey there this is a real secret'

Or, just define myrealsecret as a bytes object to begin with:

>>> myrealsecret = b'Hey there this is a real secret'
>>> secret + myrealsecret
b'a very secret messageHey there this is a real secret'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251