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.5k Golang : Get terminal width and height example
+21.6k Golang : Strings to lowercase and uppercase example
+13.6k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+10.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+7.3k Golang : How to check variable or object type during runtime?
+25k Golang : Convert file content into array of bytes
+4.8k Unix/Linux : How to open tar.gz file ?
+5.6k Golang : Skip or discard items of non-interest when iterating example
+35.3k Golang : Convert(cast) int64 to string
+5.7k Get Facebook friends working in same company
+6.7k Golang : Grayscale Image