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
+9.5k Android Studio : Indicate progression with ProgressBar example
+6.2k PHP : Get client IP address
+11.6k Get form post value in Go
+8.2k How to show different content from website server when AdBlock is detected?
+6k Golang : Generate multiplication table from an integer example
+12k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+12.5k Golang : Extract part of string with regular expression
+7.4k Golang : How to convert strange string to JSON with json.MarshalIndent
+5.7k Swift : Get substring with rangeOfString() function example
+26.3k Golang : Calculate future date with time.Add() function
+12.9k Golang : http.Get example