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
+3.8k Javascript : Access JSON data example
+22.6k Golang : Fix type interface{} has no field or no methods and type assertions example
+22.1k Golang : Randomly pick an item from a slice/array example
+6.6k Golang : Dealing with struct's private part
+7.9k Linux/Unix : fatal: the Postfix mail system is already running
+6.1k Golang : Calculate BMI and risk category
+8.9k Golang : Turn string or text file into slice example
+25.5k Golang : Encrypt and decrypt data with AES crypto
+32.9k Golang : Proper way to set function argument default value
+16.5k Golang : delete and modify XML file content