-4

I wrote some simple test code to experiment with.

#begin code Python 2.7.12 running in Windows command window
import re
s2='''corn grows
higher\n
 still.
'''

print (s2)
print (re.sub('\n', '~', s2),"test a")
print (re.sub(r'\n', '~', s2),"test ar")
print (re.sub('\s', '~', s2),"test b")
print (re.sub(r'\s', '~', s2),"test br")

##begin output to screen:####################

corn grows
higher

 still.

('corn grows~higher~~ still.~', 'test a') ('corn grows~higher~~ still.~', 'test ar') ('corn~grows~higher~~~still.~', 'test b') ('corn~grows~higher~~~still.~', 'test br')

  1. Why does the "r" for raw string not make a difference for this code?

  2. When does that "r" not make a difference even tho there are special characters?

Is this really a topic that has been covered before? Come on. I looked.|

CL1
  • 1
  • 3
  • 3
    Does this answer your question? [What exactly is a "raw string regex" and how can you use it?](https://stackoverflow.com/questions/12871066/what-exactly-is-a-raw-string-regex-and-how-can-you-use-it) – AlexisG Apr 03 '21 at 19:20
  • This is not directly relevant to your question, but as a beginner you should not be investing time in learning Python 2. Those of us who still write it do so because we have to support or migrate legacy code. It's apparent from your `print()` calls that the source you are learning from rightly expects you to be writing Python 3. Heed that expectation. – BoarGules Apr 03 '21 at 23:01
  • I am working with legacy code that uses 2.7 stuff. It could be ported to Python 3, but I am not a leader. I do try to contribute some stuff. The fact that 2.7.10 or so is mostly not adding new features may be an advantage vs an evolving language. – CL1 Apr 04 '21 at 23:13

1 Answers1

0

From the python docs, the re module treats any escape sequence with single slash and double slash as the same. In other words '\\n' and '\n' are treated as the same in a string, along with '\\s' and '\s', '\\r' and '\r', etc.

Abc Bcd
  • 76
  • 1
  • 6
  • Thanks. While I have not yet found "the re module treats any escape sequence with single slash and double slash as the same" in the docs, that certainly matches what I see happening. – CL1 Apr 03 '21 at 21:39