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.3k JavaScript : Rounding number to decimal formats to display currency
+5k Unix/Linux : How to archive and compress entire directory ?
+36.8k Upload multiple files with Go
+18.7k Golang : Clearing slice
+14.2k Golang : Rename directory
+10.7k Golang : Fix - does not implement sort.Interface (missing Len method)
+31.8k Golang : Convert []string to []byte examples
+8k Useful methods to access blocked websites
+21.6k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+19.3k Golang : Archive directory with tar and gzip
+3k Golang : Fix go-cron set time not working issue
+18.7k Golang : Calculate entire request body length during run time