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
+11.8k Golang : Convert decimal number(integer) to IPv4 address
+13.2k Golang : error parsing regexp: invalid or unsupported Perl syntax
+15.6k Golang : Get current time from the Internet time server(ntp) example
+55k Golang : Unmarshal JSON from http response
+11.5k Golang : Calculations using complex numbers example
+15.4k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+21.2k Golang : How to read float value from standard input ?
+26.6k Golang : Find files by extension
+16.9k Golang : Covert map/slice/array to JSON or XML format
+5.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+7.1k Golang : alternative to os.Exit() function
+19.5k Golang : Set or Add HTTP Request Headers