-1

I'm new to Python's \x00 string formatting and I was wondering if there is a nice pythonic way of doing something like below? I would like to dynamically insert the \x formatting into my python strings.

# Is there a way get a similar effect to this?

s = "commandstring \x{}\x{}".format('00', '00')
s = "commandstring \x%s\x%s" % ('00', '00')

Some of my strings will be regular text and numbers, but I also need to insert the Hex values

1
  • 2
    Do you want the string to contain "\x00" or do you just want the character with that char code?
    – hlt
    Aug 14, 2014 at 17:36

2 Answers 2

2

\x00 represents a single byte. Produce those single bytes directly:

>>> "commandstring {}{}".format('\x00', '\x00')
'commandstring \x00\x00'

or use the chr() function to produce the byte given an integer:

>>> "commandstring {}{}".format(chr(0), chr(0))
'commandstring \x00\x00'

The \xhh notation is syntax that can only be used in a string literal. You could construct the syntax then have Python explicitly interpret that with eval(), ast.literal_eval or the raw_string codec, but that is usually not what you need in the first place.

3
  • What about chr(95)? it returns '_', but I would like '\x5F'. I guess this is the same value to linux tho so I'm not sure it matters. I was told I might also be able to use struct.pack?
    – Matt
    Aug 14, 2014 at 17:52
  • @Matt: No, it returns the byte with value 0x5F, the string representation uses printable ASCII characters where possible.
    – Martijn Pieters
    Aug 14, 2014 at 17:54
  • @Matt: you are confusing byte representations with values here. Either you can have 4 characters, the \ backslash, the x and the two characters representing hexadecimal digits, or you can have the one character at that codepoint. You are not using \x63 for the c in commandstring either, for example.
    – Martijn Pieters
    Aug 14, 2014 at 17:55
1

I think what you want here is the %x placeholder. Try the following:

s = "commandstring \x%x\x%x" % (50, 95)

It will give you

s = "commandstring \x32\x5f"

But, you need to pass integers for it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.