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
+8.6k Golang : Find network service name from given port and protocol
+12.4k Golang : Remove or trim extra comma from CSV
+8.2k Golang : Generate Datamatrix barcode
+6.2k Grep : How to grep for strings inside binary data
+21.8k Golang : Match strings by wildcard patterns with filepath.Match() function
+4.8k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+15.4k Golang : Get current time from the Internet time server(ntp) example
+14.3k Golang : How to get URL port?
+18.9k Golang : Calculate entire request body length during run time
+22.3k Generate checksum for a file in Go
+30.7k Golang : Calculate percentage change of two values
+11.8k Golang : Pagination with go-paginator configuration example