Home > Back-end >  What is the error show underline in this Python code
What is the error show underline in this Python code

Time:04-01

I'm just a beginner in Python. Do you know why it's underline here? enter image description here

CodePudding user response:

This is a normal string, that has escaping mechanism by prepending a backslash before certain characters to create special meanings for them (e.g. \n, \u791c...) or to strip them of the special meaning (\", \\...). However, the sequence \d is not defined, and "\d" is equivalent to "d".

(Thus, your code would have matched only strings that consist of any number of repetitions of the letter d and nothing else, such as "d", "dd" or "dddddddd", which is presumably not what you wanted - which is why the editor is warning you something might smell there.)

This is rather inconvenient for regular expressions, which also use backslash for escaping, so each backslash has to be additionally escaped. To make a regular expression that contains \d, you have to double up the backslashes so that the backslash survives to be contained in the string: \\d. If you actually want to match a backslash in a regular expression, you must escape it in the regular expression - but you also need to escape it in the string literal, resulting in a ridiculous-looking "\\\\".

For this purpose, Python has "raw strings", where the backslash escape does not work - a backslash is just a backslash. To make a raw string, just prepend r.

Thus, you should have written either of these instead:

"^\\d $"
r"^\d $"
  • Related