Python : Convert(cast) string to bytes example
Problem :
You have couple of string variables in Python and you want to convert or type cast the string variables to bytes. How to do that?
Solution :
For Python 3 :
Declare a string variable and find out the variable type with type(var)
var = "str"
type(var)
<class 'str'> // type string
Convert string type to bytes with encode() function
var = "str".encode()
type(var)
<class 'bytes'> // type bytes
Alternatively, you can convert or type cast the string into bytes...straightaway by adding the b character pre-fix.
var = b"str"
type(var)
<class 'bytes'> // type bytes
See also : Python : Convert(cast) bytes to string example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.5k PHP : Extract part of a string starting from the middle
+15.9k Golang : convert string or integer to big.Int type
+5.8k PageSpeed : Clear or flush cache on web server
+12.1k Golang : Extract part of string with regular expression
+8.5k Golang : On lambda, anonymous, inline functions and function literals
+5.1k Unix/Linux : How to archive and compress entire directory ?
+16k Golang : Find out mime type from bytes in buffer
+17.3k How to enable MariaDB/MySQL logs ?
+15.8k Golang : How to check if input from os.Args is integer?
+26.4k Golang : How to check if a connection to database is still alive ?
+13.8k Golang : Fix image: unknown format error
+28.4k Golang : Detect (OS) Operating System