Home > other >  How to change `23` to b`\x23` in python?
How to change `23` to b`\x23` in python?

Time:11-07

I want to change a string variable to bytes,like 23 to b\x23. I tried

var_a= `23`
var_b = b'\x' var_a   #=>TypeError: sequence item 0: expected a bytes-like object, str found
var_b = b'\\x' var_a  #=> \\x23
var_b = br'\x' var_a  #=> \\x23

How to change the string to bytes like this in python?

CodePudding user response:

You can do this with chr:

character = 0x23 # use hex encoding
string = chr(character)
print(string)
# outputs '#'

CodePudding user response:

You could create a hex value from 23 first:

>>> expected =  b'\x23'
>>> var_a = 23  # or '23' as string!
>>> result = chr(int(f"0x{var_a}", 0)).encode('utf-8')
>>> print(result == expected)
True
>>> print(result, expected)
b'#' b'#'

CodePudding user response:

Try this, first convert string to int, next from int to hex:

var_a = "23"
var_b = int(var_a, 16)
var_c = hex(var_b)

CodePudding user response:

I think you are probably looking for the built-in bytes function: https://docs.python.org/3/library/functions.html#func-bytes

a = '23'
b = bytes(a, 'utf-8')
  • Related