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
+18.7k Golang : Generate thumbnails from images
+7.1k Golang : Squaring elements in array
+5.8k Unix/Linux/MacOSx : Get local IP address
+7k Golang : Levenshtein distance example
+10.2k Golang : Identifying Golang HTTP client request
+13k Python : Convert IPv6 address to decimal and back to IPv6
+18.6k Golang : Set, Get and List environment variables
+14k Golang : Human readable time elapsed format such as 5 days ago
+9.6k Javascript : Read/parse JSON data from HTTP response
+6.1k Golang : Function as an argument type example
+16.5k Golang : Test floating point numbers not-a-number and infinite example
+19.1k Golang : Clearing slice