Netro
Netro

Reputation: 7297

Python regex '\s' vs '\\s'

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?

Upvotes: 3

Views: 3722

Answers (2)

shx2
shx2

Reputation: 64308

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

Upvotes: 6

John La Rooy
John La Rooy

Reputation: 304147

\ 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

Upvotes: 2

Related Questions