简体   繁体   中英

python string.format and invalid \x escape

I'm trying to format a string with some \\x inside in python.

When I use:

print '\x00\x00\xFF\x00'

it works nicely and print . But when I try to format the string:

print '\x{}\x{}\x{}\x{}'.format('00','00','FF','00')

I get this error:

ValueError: invalid \x escape

The problem when I escape the backslash like this:

print '\\x{}\\x{}\\x{}\\x{}'.format('00','00','FF','00')

It prints:

\x00\x00\xFF\x00

And not the little like the non-formatted string.

chr and bytearray seem interesting for example:

print chr(0x00),chr(0x00),chr(0xFF),chr(0x00) or print bytearray([0x00, 0x00, 0xFF, 0x00])

prints , but when I try to format them, I get a SyntaxError.

I found some interesting posts like:

But I'm still stuck...

How to print a formatted string with \\x inside?

(I'm using python 2.7 but I can use an other version.)

Thank you

The objective is to create a format string that will print characters, given string representations of hex values that correspond to unicode code points, so that something like this

for var1 in 'FF','00','38': 
    print '\x{}\x{}\x{}\x{}'.format(var1,'00','FF','00')

will output

8

The trick is to convert the hex values to integers, using the int builtin function, then use the c string format code to convert the integer value to the corresponding unicode character.

for v in ('ff', '00', '38'):
    print '{:c}{:c}{:c}{:c}'.format(*[int(x, 16) for x in [v, '00', 'ff', '00']])

�� 
� 
8�

From the docs :

c : Character. Converts the integer to the corresponding unicode character before printing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM