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
+20.9k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+15.1k Golang :Trim white spaces from a string
+8.2k Golang : Temperatures conversion example
+4.9k Golang : Struct field tags and what is their purpose?
+4k Golang : Print instead of building pyramids
+6.4k Android Studio : AlertDialog to get user attention example
+6.3k Golang : Of hash table and hash map
+12k Golang : Count number of runes in string
+11.4k Golang : Remove or trim extra comma from CSV
+8.7k Golang : Bcrypting password
+9k Golang : Channels and buffered channels examples
+8k Golang : Serving HTTP and Websocket from different ports in a program example