problem with newlines in regexp substitution

Discussion in 'Python' started by Florian Schulze, Feb 23, 2006.

  1. See the following results:

    Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on
    Type "help", "copyright", "credits" or "license" for more information.'\\n'

    Why is the behaviour of the regexp substitution so weird and can I prevent
    that? It breaks my asumptions and thus my code.

    Florian Schulze
    Florian Schulze, Feb 23, 2006
    1. Advertisements

  2. Florian Schulze

    James Stroud Guest

    "Why" questions are always tough to answer. E.g.: Why are we here?

    The answer to "what is happening" is much easier. Strings passed to the
    regex engine are processed first, so escapes must be escaped. This is
    why raw strings were invented. If it weren't for these, I'd still be
    using perl. In raw strings, as you have noticed, a '\' is already
    escaped. In the olden days, you'd have to type "\\\\" to mean a literal
    backslash, so creating a literal backslash in a regex that produced a
    string that would then itself be used in a regex would be
    '\\\\\\\\\\\\\\\\', which scared me away from Python for a couple of
    years (rmember, the final printed product would be '\').

    That patently doesn't answer your question, but here is something to ponder:

    py> s.replace('1',repl)[0]
    py> print s.replace('1',repl)

    James Stroud, Feb 23, 2006
    1. Advertisements

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.