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
+16.5k Golang : Read data from config file and assign to variables
+16.5k Convert JSON to CSV in Golang
+8k Golang : How to get username from email address
+14.8k Golang : Generate universally unique identifier(UUID) example
+7.1k Golang : Variadic function arguments sanity check example
+8.5k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+18.3k Golang : How to Set or Add Header http.ResponseWriter?
+5.8k Golang : Warp text string by number of characters or runes example
+15.4k Golang : Send email and SMTP configuration example
+4.5k PHP : Fix Call to undefined function curl_init() error
+7k Golang : Handle Palindrome string with case sensitivity and unicode
+20.9k Golang : Securing password with salt