原始字符串
原始字符串以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字符串。
所以这个可以忽略吧。
本文介绍了Python中如何使用原始字符串处理反斜线转义问题,并对比了普通字符串与原始字符串的区别。同时,提到了Unicode字符串的基本使用。
1万+

被折叠的 条评论
为什么被折叠?



