0

If I have a string

s = 'this is a \n tennis ball'

and if perform in python:

s.replace("\n", "nice")

the output is:

"this is a nice tennis ball"

On the other hand if I perform in python

s.replace(r"\n","nice"), 

the output is

"this is a \n tennis ball"

What is the difference between using simple plain string and using r raw string and what is the reason for these different outputs.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    Note that this has nothing to do with `str.replace()`. You should really look at the different values `'\n'` and `r'\n'` produce. – Martijn Pieters Apr 28 '18 at 18:06

1 Answers1

0

An 'r' string literal makes the '\' character represent an actual '\' character instead of a special character and it behaves as a raw string.

In the string s = 'this is a \n tennis ball', if you add an 'r', so its s = r'this is a \n tennis ball' it will recognize the '\' sign as a regular raw '\' sign and recognize it when you use the r'\' while using s.replace()

I might not have been very clear in my explanation, I suggest reading the answer to What exactly do “u” and “r” string flags do, and what are raw string literals?

Flaming_Dorito
  • 486
  • 3
  • 11
  • The behaviour follows directly from an understanding of what raw string literals are: no replacement occurs, because *the string described by the raw string literal is not actually a substring of the larger text*. On this basis, I have closed the question as a duplicate. – Karl Knechtel Jul 31 '22 at 04:41