2016年1月9日
1、\'\'\'作用: 可以表示 \"多行注释\" 、\"多行字符串\" 、\"其内的单双引号不转义\"
2、r 代表的意思是: raw
3、r 只对其内的反斜杠起作用(注意单个 \\ 的问题)
raw string 有什么用处呢? raw string 就是会自动将反斜杠转义。
>>> print(\'\\n\')
>>> print(r\'\\n\')
\\n
>>>
(注:出现了两个空行是因为 print() 会自动添加一个空行)
再举个例子:
>>> r\'\\\\\\\\\\\\\' == \'\\\\\\\\\\\\\\\\\\\\\\\\\'
True
>>> print(\'\\\\\\\\\\\\\\\\\\\\\\\\\')
\\\\\\\\\\\\
>>> print(r\'\\\\\\\\\\\\\')
\\\\\\\\\\\\
>>>
上述就是raw string 的基本功能。
所谓的
print(r\'\'\'1
2
3
4\'\'\')
和
print(\'\'\'1
2
3
4\'\'\')
效果一样的原因其实就在于
三引号内没有 \\
所以 r
英雄无用武之地
有一点要注意的是,raw string 并不能让诸如 print(r\’\\\’) 起作用。因为在
编译时
Python还是会尝试使用反斜杠来转义单引号,从而造成字符串没有终止的问题.
>>> print(r\'C:\\Windows\\System32\')
C:\\Windows\\System32
>>> print(\'C:\\\\Windows\\\\System32\')
C:\\Windows\\System32
>>> print(\'C:\\Windows\\System32\')
C:\\Windows\\System32
>>>
最后一行也可以生效的原因是,\\W
和 \\S
什么都不是。所以在这个例子中Python发现“无法转义”,所以就不做任何转义而直接打印转义符。但是:
>>> print(\'C:\\Windows\\System32\\new\')
C:\\Windows\\System32
ew
>>> print(r\'C:\\Windows\\System32\\new\')
C:\\Windows\\System32\\new
就不一样了。