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
+4.3k Golang : Valued expressions and functions example
+21.4k Golang : How to read float value from standard input ?
+21.5k Golang : Encrypt and decrypt data with TripleDES
+35k Golang : Upload and download file to/from AWS S3
+9.3k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+9.4k Golang : Get all countries currencies code in JSON format
+4.6k Linux : sudo yum updates not working
+15.3k Golang : Get all local users and print out their home directory, description and group id
+21k Golang : Sort and reverse sort a slice of strings
+24.9k Golang : Create PDF file from HTML file
+5.7k Get website traffic ranking with Similar Web or Alexa
+9.7k Random number generation with crypto/rand in Go