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
+15.6k Golang : How to generate QR codes?
+25.8k Golang : Convert CSV data to JSON format and save to file
+14.6k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+17.9k Golang : Get RGBA values of each image pixel
+3.9k Golang : Calculate a pip value and distance to target profit example
+5.9k Mac OSX : Find large files by size
+9.4k Golang : ISO8601 Duration Parser example
+5.7k Get Facebook friends working in same company
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+35.3k Golang : Convert(cast) int64 to string
+4.5k Python : Delay with time.sleep() function example
+13.1k Golang : Recombine chunked files example