1

Python has this way of specifying regular expression pattern, where all special character should not be treated as special. From the docs:

So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline.

Why then does this works?

import re print re.split(r"\n", "1\n2\n3") 

The first argument should be "\" and "n" and the second one should contain two newlines. But it prints:

['1', '2', '3'] 

1 Answer 1

2

The first one does contain backslash-and-n, but in regular-expression-language, backslash-and-n means newline (just like it does in Python string syntax). That is, the string r"\n" does not contain an actual newline, but it contains something that tells the regular expression engine to look for actual newlines.

If you want to search for a backslash followed by n, you need to use r"\\n".

The point of the raw strings is that they block Python's basic intepretation of string escapes, allowing you to use the backslash for its regular-expression meaning. If you don't want the regular-expression meaning, you still have to use two backslashes, as in my example above. But without raw strings it would be even worse: if you wanted to search for literal backslash-n without a raw string, you'd have to use "\\\\n". If the raw string blocked interpretation of the regular expression special characters (so that plain "\n" really meant backslash-n), you wouldn't have any way of using the regular expression syntax at all.

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm...and how do I search for "\" followed by "n"?
@BrenBarn It's been some time since you answered this but I hope someone could help. I tried to match a backslash followed by n (text='\\n')and I do re.match(r'\\n',text). The result is <_sre.SRE_Match object; span=(0, 2), match='\\n'> . Why would i get \\n in instead of \n?
@Le0: The string '\\n' represent a backslash followed by n, just as it does in your text string. If you don't understand what's going on, look up many other questions on here about extra backslashes, raw strings, etc. If you still don't understand, post a separate question rather than asking in a comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.