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
+21.6k Golang : Strings to lowercase and uppercase example
+14.1k Golang : Get query string value on a POST request
+9.5k Swift : Convert (cast) String to Integer
+6k Golang : Mapping Iban to Dunging alphabets
+17.2k Golang : Write file with io.WriteString
+8.4k Golang : Get all countries currencies code in JSON format
+6.8k Golang : Scan files for certain pattern and rename part of the files
+10.5k Golang : Convert decimal number(integer) to IPv4 address
+4.7k Golang : Grab news article text and use NLP to get each paragraph's sentences
+21.4k Golang : simulate tail -f or read last line from log file example
+9.7k Golang : Simple image viewer with Go-GTK