problem with newlines in regexp substitution

F

Florian Schulze

See the following results:

Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on
win32
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.

Regards,
Florian Schulze
 
J

James Stroud

Florian said:
See the following results:

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


'\\n'


'\\n'


'\\n'

'\n'

'\\n'

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

Regards,
Florian Schulze

"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)
\n

James
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top