1

Let's say I have an escaped hex value in a string:

val = "\x70"

and the function

def foo(input):
  for byte in bytes(input, "utf-8"):
    print(byte)

If I call

foo(val) #prints 112

The function works as desired. But what if I don't know the value of the hex code I want to escape, yet want to escape it and iterate through it the same way?

unknown_until_runtime = "70"
val = "\x" + unknown_until_runtime

Results in a

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

I have the option of escaping the escape character, but this then breaks the functionality of the iterator in foo():

unknown_until_runtime = "70"
val = "\\x" + unknown_until_runtime
foo(val) #prints 92 120 55 48

Instead of escaping the entire byte as intended, this "string construction method" does not escape anything, and simply creates a "string of chars" that does not function the way I want it. And for the life of me, I find a way to obtain this "escaped byte string" when the values are unknown until runtime. Any suggestions?

martineau
  • 119,623
  • 25
  • 170
  • 301
austinstout
  • 1,180
  • 1
  • 11
  • 14

1 Answers1

2

If you change your function to the following, it should work:

def foo(input_str)
    for byte in bytes('\\x' + input_str, 'utf-8').decode('unicode_escape'):
        print(byte)

Solution inspired by this answer.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46