Translating escaped characters

Discussion in 'Python' started by Henrik S. Hansen, Nov 1, 2004.

  1. How do you best go about translating characters like '\\n' to '\n'?
    This is for a configuration file parser, where the "backslash
    convention" is supported.

    The naive approach -- re.sub('\\\\(.)', '\\\1', s) -- doesn't work, of
    course. The best I've come up with so far is a special case for every
    character to be translated. There must be an easier way?

    --
    Henrik S. Hansen http://freecode.dk/~hsh/
    Computer science (software engineering) student
    Free Software Foundation member #1702 (http://member.fsf.org)
    Henrik S. Hansen, Nov 1, 2004
    #1
    1. Advertising

  2. Henrik S. Hansen <hsh <at> freecode.dk> writes:

    >
    > How do you best go about translating characters like '\\n' to '\n'?


    Is this what you're looking for?

    >>> '\\n'.decode('string_escape')

    '\n'
    >>> '\n'.encode('string_escape')

    '\\n'

    There's some info about it here:

    http://docs.python.org/lib/node127.html

    and searching Google Groups shows up a few things too:

    http://groups.google.com/groups?q=escape sequences&
    meta=group%3Dcomp.lang.python.*

    (Sorry, the URL wrapped.)

    Steve
    Steven Bethard, Nov 1, 2004
    #2
    1. Advertising

  3. Steven Bethard <> writes:

    >> How do you best go about translating characters like '\\n' to '\n'?

    >
    > Is this what you're looking for?
    >
    >>>> '\\n'.decode('string_escape')

    > '\n'
    >>>> '\n'.encode('string_escape')

    > '\\n'


    Precisely, thank you.

    --
    Henrik S. Hansen http://freecode.dk/~hsh/
    Computer science (software engineering) student
    Free Software Foundation member #1702 (http://member.fsf.org)
    Henrik S. Hansen, Nov 2, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    751
  2. Ben Finney
    Replies:
    2
    Views:
    333
    Josiah Carlson
    Apr 3, 2004
  3. Derek Basch
    Replies:
    2
    Views:
    444
    Derek Basch
    Mar 25, 2005
  4. Thea
    Replies:
    2
    Views:
    615
  5. metaperl
    Replies:
    3
    Views:
    325
    Nick Craig-Wood
    Dec 8, 2006
Loading...

Share This Page