nuggets
nuggets

Reputation: 179

Convert escape characters in strings (like "\\n" - two characters) into ASCII character (newline)

My program got a string from the command line arguments, that contains many escapes characters.

./myprog.py "\x41\x42\n"

When I print "sys.argv[1]". I got on the screen:

\x41\x42\n

Is there a simple way to do that the program print instead:

AB[newline]

Upvotes: 2

Views: 142

Answers (2)

boaz_shuster
boaz_shuster

Reputation: 2925

Try passing the argument in the following way:

./myprog.py $'\x41\x42\n'

The $'...' notation is allowed to be used together with \x00-like escape sequences for constructing arbitrary byte sequences from the hexadecimal notation.

Another way to fix this is to do what @Barak suggested here -- that is converting the hex characters. It just depends on what you find easy for you.

Upvotes: 1

barak manos
barak manos

Reputation: 30146

The string passed to your program is '\\x41\\x42\\n'.

I don't think there is a simple way to revert it back into 'AB\n'.

You'll have to split the string by '\\', and treat each element separately.

If your string is always of the form '\\x..\\x..\\x..\\n', then you can do this:

print ''.join([chr(int('0'+k,16)) for k in sys.argv[1].split('\\')[1:-1]])

Upvotes: 2

Related Questions