我有两个简单的表达式\s和\\s,这两个表达式都可以匹配This is Sparta!!。 >>> re.findall('\\s',"This is Sparta") [' ', ' '] >>> re.findall('\s',"This is Sparta") [' ', ' '] 我在这里有些困惑。 \ 用于转义特殊字符,而 \s 代表空格,但是在这里两者的作用是什么呢?
不要混淆Python级别的字符串转义和正则表达式级别的字符串转义。由于在Python级别上,“s”不是一个可转义的字符,因此解释器会将形如“\s”的字符串理解为两个字符“\”和“s”。将“s”替换为“n”(例如),它就被解析为换行符。'\s' == '\\s' True '\n' == '\\n' False
\\
是转义字符。https://docs.python.org/2/howto/regex.html#the-backslash-plague - desired login