原始字符串
原始字符串以r开头,可以在原始字符串中放入任何字符,但不能以反斜线“\”结尾,用来防止反斜线转义!
在普通字符串中,反斜线“\”会转义,在字符串中通常不能直接加入的内容。
如:
>>>print("C:\nowhere")
>>C:
owhere
要输出C:\nowhere,必须加反斜杠转义。
>>> print("C:\\nowhere")
C:\nowhere
>>>
在这种情况下原始字符串就派上用处了。原始字符串不会把反斜线“\”当做特殊字符,它会把输入的每个字符都按书写格式输出。原始字符串以r开头,可以在原始字符串中放入任何字符。
>>> print("C:\Users\Administrator\Desktop") #反斜线\会报错。
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> print("C:\\Users\\Administrator\\Desktop") #使用\反斜线转义
C:\Users\Administrator\Desktop
>>> print(r"C:\Users\Administrator\Desktop") #使用r原始字符串更方便
C:\Users\Administrator\Desktop
注意:
不能在原始字符串结尾输入反斜线,也就是原始字符串结尾不能是反斜线“\”!!!
>>> print(r"C:\Users\Administrator\Desktop\")
SyntaxError: EOL while scanning string literal
Unicode字符串
>>> print(u"hello wolwd")
hello wolwd
>>>
Unicode字符串使用u前缀,就像原始字符串使用r一样。
注意:在python3中,所有的字符串都是Unicode字符串。
所以这个可以忽略吧。