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
+10k Golang : Compare files modify date example
+39.4k Golang : Remove dashes(or any character) from string
+55k Golang : Unmarshal JSON from http response
+10.3k Golang : Generate random integer or float number
+20.4k Nginx + FastCGI + Go Setup.
+10.6k Android Studio : Checkbox for user to select options example
+14.3k Golang : How to filter a map's elements for faster lookup
+10.3k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+12k Golang : Get remaining text such as id or filename after last segment in URL path
+31.3k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+6.4k Golang : Convert an executable file into []byte example
+7.8k Golang : What fmt.Println() can do and println() cannot do