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
+14.1k Golang : Validate hostname
+6.7k Golang : Reverse a string with unicode
+10.3k Golang : Generate DSA private, public key and PEM files example
+6.6k Golang : Generate human readable password
+23.4k Golang : convert rune to integer value
+5.2k Golang : Detect face in uploaded photo like GPlus
+10.6k Golang : Handle API query by curl with Gorilla Queries example
+22.5k Golang : Generate MD5 checksum of a file
+33.7k Golang : Strip slashes from string example
+6.5k SSL : How to check if current certificate is sha1 or sha2 from command line
+30.9k Golang : Convert []string to []byte examples
+5.9k Golang : How to call function inside template with template.FuncMap