Why does the escape character / need to be added after r in the regular expression of python?

topic description

The

requirement is to replace the better in text with that strong
in the regular mode of the sub method, where I have added r to indicate escape.
Why add a\, written as r"\ * (. *?)\ *?
Why can"t you just write ringing * (. *?) *?
what do the two here do?

related codes

text = "Beautiful is better than ugly."
re.sub (r"\ * (. *?)\ *," , text)

what result do you expect? What is the error message actually seen?

in the regular mode of the sub method, I have added r in front to indicate escape.
Why add a\, written as r"\ * (. *?)\ *?
Why can"t you just write ringing * (. *?) *?

what I need is between * and *, and I don"t need * to represent the quantity, so why add\ * after r to escape *?


in fact, there are two levels of escape, one is string assignment, the other is regular engine escape

Let's start with r in front of the string. python escapes the escaped characters in the string by default, for example, \ n wraps lines directly. If you want to print \ n , you need to define \ n , while the string is preceded by r , so it will not be escaped.

>>> print('\n')


>>> print('\\n')
\n
>>> print(r'\n')
\n

besides * , * is not an escaped character in a string, but it has a special meaning for regular expressions. The reason for adding \ * is to make the regular engine think of it as a normal string. If your regular is just a simple r'\ * (. *?)\ * , whether you add r or not, the result is the same. python string assignment will not escape it

.
>>> print(r'\*(.*?)\*')
\*(.*?)\*
>>> print('\*(.*?)\*')
\*(.*?)\*
Menu