Skip to content

Instantly share code, notes, and snippets.

@normoes
Last active October 15, 2018 09:23
Show Gist options
  • Save normoes/78a9204e543061f7a1de1c5316869f8b to your computer and use it in GitHub Desktop.
Save normoes/78a9204e543061f7a1de1c5316869f8b to your computer and use it in GitHub Desktop.
byte and string in python
>>> a = 'world'    
>>> b = b'hello '    
>>> type(a)
<class 'str'>
>>> type(b)
<class 'bytes'>    

What's new in python3 shows:

>>> str.encode(a)
b'world'
>>> bytes(a, encoding='utf-8')
b'world'
>>> bytes.decode(b)
'hello'
>>> str(b, encoding='utf-8')
'hello'

Also works:

>>> type(b.decode())
<class 'str'>
>>> b.decode()
'hello'
>>> type(str.encode(a))
<class 'bytes'>
>>> type(a.encode())
<class 'bytes'>
>>> a.encode()
b'world'

For hex:

#assuming python3
# os.random(8) return b'' (bytes)
paymentId = binascii.hexlify(os.urandom(8))  # bytes
return bytes.decode(paymentId)  # str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment