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.1k Golang : A program that contain another program and executes it during run-time
+12.8k Golang : Tutorial on loading GOB and PEM files
+26.4k PHP : Count number of JSON items/objects
+14.4k Golang : Force download file example
+9.9k Golang : Get UDP client IP address and differentiate clients by port number
+9.7k Golang : Underscore string example
+14.3k Golang : How to get Unix file descriptor for console and file
+19.8k Golang : Convert PNG transparent background image to JPG or JPEG image
+44.6k Golang : Read tab delimited file with encoding/csv package
+6.1k Golang : Decode XML data from RSS feed
+5.7k Golang : Combine slices of complex numbers and operation example
+11.1k Golang : Convert a rune to unicode style string \u