Backslash Escapes

Chris Angelico rosuav at gmail.com
Sun Dec 25 22:58:36 EST 2011


On Mon, Dec 26, 2011 at 12:04 PM, Felipe O <pip.261 at gmail.com> wrote:
> Hi all,
> Whenever I take any input (raw_input, of course!) or I read from a
> file, etc., any backslashes get escaped automatically. Is there any
> elegant way of parsing the backslashes as though they were written in
> a python string... I guess the alternative is to make a dictionary of all the escapes I
> want to support, but that sounds tedious and error-prone.

The question really is: Are you looking to support some backslash
escapes, or are you looking to imitate Python? If the former, I
recommend making a specific list of what you support; every language
has its own, usually including some obscurities, and if all you need
is a few basics like \n, \t, \\, etc, then you probably don't want to
support \123 and \u1234 notations for arbitrary insertion of
characters. But if you actually want to imitate a Python string
literal, eval is almost certainly the easiest way; and if you want a
safer version:

http://docs.python.org/library/ast.html#ast.literal_eval

I'm not sure how well suited this is for parsing a string for its
escapes, but if you're looking to imitate Python, it may be easier to
tell people that the value must be enclosed in quotes - thus making it
an expression.

ChrisA



More information about the Python-list mailing list