Interpreting \ escape sequences in strings
Paul Watson
pwatson at redlinec.com
Sat Mar 13 23:07:59 EST 2004
"Peter Otten" <__peter__ at web.de> wrote in message
news:c302qi$3lj$04$1 at news.t-online.com...
> Paul Watson wrote:
>
> > 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
>
> If I'm understanding you correctly:
>
> <args.py>
> import sys
> print sys.argv[1].decode("string_escape")
> </args.py>
>
> $ python args.py "winter\nof\012our\x0Adiscontent"
> winter
> of
> our
> discontent
>
> Peter
I did have not explained it clearly. I want the user to specify a string
that I will put between words in the output. The user specified string can
have escape sequences. For example, the user wants to put a binary 1 (\001)
between each output word.
import sys
words = ['now', 'is', 'the', 'time']
print '\001'.join(words) #this works
print sys.argv[1].join(words) #this fails
$ ./putbetween.py '\001'
now?is?the?time
now\001is\001the\001time
More information about the Python-list
mailing list