Interpreting \ escape sequences in strings

Paul Watson pwatson at redlinec.com
Sat Mar 13 16:20:20 EST 2004


How can I get the escapes from a command line parameter interpreted?

The user provides a string on the command line.  The string might contain
traditional escapes such as \t, \n, etc.  It might also contain escaped
octal or hex such as \001 or \x09.

The escapes are coming into sys.argv[] without shell interpretation.  Do I
need to use the compile module to make this work?  Any suggestions?

===
$ cat ./try_arglen2.py
#! /usr/bin/env python
import sys, StringIO
print sys.argv[1]

print sys.argv[1] % ()

sf = StringIO.StringIO()
print >> sf, sys.argv[1],
c = sf.getvalue()
sf.close()
print "now" + c + "is" + c + "the"

# This works because the interpreter is processing the escapes.

sf = StringIO.StringIO("\001")
c = sf.getvalue()
sf.close()
print "now" + c + "is" + c + "the"

===
$ ./try_arglen2.py '\001'
\001
\001
now\001is\001the
now?is?the





More information about the Python-list mailing list