I have simple expression \\s
and \\\\s
. Both expression matches This is Sparta!!
.
>>> re.findall('\\s',"This is Sparta")
[' ', ' ']
>>> re.findall('\s',"This is Sparta")
[' ', ' ']
I am confused here. \\
is used to escape special character and \\s
represents white space but, how both are acting here?
Don't confuse python-level string-escaping and regex-level string-escaping. Since s
is not an escapable character at python-level, the interpreter understand a string like "\\s" as the two characters "\\" and "s". Replace "s" with "n" (for example), and it understands it as the newline character.
'\s' == '\\s'
True
'\n' == '\\n'
False
\\
only escapes the following character if the escaped character is valid
>>> len('\s')
2
>>> len('\n')
1
compare with
>>> len('\\s')
2
>>> len('\\n')
2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.