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.

6
  • Not a dupe........ although i do see where your going with that assumption. im asked how i can use my two variable references together. Commented Dec 22, 2015 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. Commented Dec 22, 2015 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. Commented Dec 22, 2015 at 23:21
  • 3
    Ah, here's the dupe: stackoverflow.com/q/606191 Commented Dec 22, 2015 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 Commented Dec 22, 2015 at 23:21

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Finally, someone who didnt just jump to conclusions. This is spot on, thank you so, so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.