convert string to bytes python code example
Example 1: bytes to string python
bytes = b'abcde'
bytes.decode("utf-8")
'abcde'
Example 2: python string to bytes
s = 'abc'
b = bytes(s, encoding='utf-8')
print(type(b))
print(b)
s = b.decode()
print('Original String =', s)
s = 'xyz'
b = s.encode(encoding='utf-8')
print(b)
s = b.decode()
print('Original String =', s)
Example 3: convert int to binary python
def decimalToBinary(n):
return bin(n).replace("0b", "")
if __name__ == '__main__':
print(decimalToBinary(8))
print(decimalToBinary(18))
print(decimalToBinary(7))
Output:
1000
1001
Example 4: python convert string to bytes
data = ""
data = "".encode()
data = b""
data = b"".decode()
data = str(b"")
Example 5: python convert string to byte array
a_string = "abc"
encoded_string = a_string. encode()
byte_array = bytearray(encoded_string)
print(byte_array)