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
+6.3k Golang : Totalize or add-up an array or slice example
+7.5k Golang : Reverse a string with unicode
+13.3k Golang : Query string with space symbol %20 in between
+13.2k Golang : How to get year, month and day?
+12k Golang : calculate elapsed run time
+11.8k Golang : Save webcamera frames to video file
+6.9k Nginx : How to block user agent ?
+17.5k Golang : How to make a file read only and set it to writable again?
+19.8k Golang : Check if os.Stdin input data is piped or from terminal
+9.4k Golang : Validate IPv6 example
+9.9k Golang : Check a web page existence with HEAD request example
+6.5k Golang : Humanize and Titleize functions