1# utf-8 is used here because it is a very common encoding, but you
2# need to use the encoding your data is actually in.
3bytes = b'abcde'
4bytes.decode("utf-8")
5'abcde'
1s = 'abc'
2
3# string to bytes using bytes()
4b = bytes(s, encoding='utf-8')
5print(type(b)) # <class 'bytes'>
6print(b) # b'abc'
7
8# bytes to string using decode()
9s = b.decode()
10print('Original String =', s) # Original String = abc
11s = 'xyz'
12
13# string to bytes using encode()
14b = s.encode(encoding='utf-8')
15print(b) # b'xyz'
16s = b.decode()
17print('Original String =', s) # Original String = xyz
1data = "" #string
2data = "".encode() #bytes
3data = b"" #bytes
4data = b"".decode() #string
5data = str(b"") #string
1a_string = "abc"
2encoded_string = a_string. encode()
3byte_array = bytearray(encoded_string)
4print(byte_array)
1#Python string to bytes:
2
3s = 'abc'
4
5# string to bytes using bytes()
6b = bytes(s, encoding='utf-8')
7print(type(b)) # <class 'bytes'>
8print(b) # b'abc'
9
10# bytes to string using decode()
11s = b.decode()
12print('Original String =', s) # Original String = abc
13s = 'xyz'
14
15# string to bytes using encode()
16b = s.encode(encoding='utf-8')
17print(b) # b'xyz'
18s = b.decode()
19print('Original String =', s) # Original String = xyz