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
+29.5k Golang : Math pow(the power of x^y) example
+12.3k Android Studio : Use image as AlertDialog title with custom layout example
+3.8k Golang : micron to centimeter example
+35k Golang : Convert(cast) int64 to string
+6.9k Golang : How To Use Panic and Recover
+6.8k Golang : Routes multiplexer routing example with regular expression control
+14k Golang : Read large file with bufio.Scanner cause token too long error
+8.1k Facebook : Getting the friends list with PHP return JSON format
+10.6k Golang : Display list of countries and ISO codes
+9k Golang : Fix go.exe is not compatible with the version of Windows you're running
+5.2k Golang : Combine slices of complex numbers and operation example
+5.4k Golang : Fixing Gorilla mux http.FileServer() 404 problem