python中字符串的反斜杠问题

时间:2021-10-15 14:45:59

1,当反斜杠中不含转义字符时可以依旧打印,结果不变,但不鼓励

>>> mystr='C:\Program Files\python\Good'
>>> mystr
'C:\\Program Files\\python\\Good'
>>> print(mystr)
C:\Program Files\python\Good

2,当反斜杠和其之后的字符组合成转义字符时,输出结果会发生改变

>>> mystr='C:\numpyPacket\Program Files\python\Good'
>>> mystr
'C:\numpyPacket\\Program Files\\python\\Good'
>>> print(mystr)
C:
umpyPacket\Program Files\python\Good

3.上述情况的解决方案一是在输出所有反斜杠处的位置,使用转义字符\,再输出其自身.二是使用原始字符串r,即在字符串之前加个小r

mystr='C:\\numpyPacket\\Program Files\\python\\Good'
>>> mystr
'C:\\numpyPacket\\Program Files\\python\\Good'
>>> print(mystr)
C:\numpyPacket\Program Files\python\Good
>>> mystr=r'C:\numpyPacket\Program Files\python\Good'
>>> mystr
'C:\\numpyPacket\\Program Files\\python\\Good'
>>> print(mystr)
C:\numpyPacket\Program Files\python\Good

4,如果要在字符串末尾连接反斜杠或双反斜杠,该如何操作

        首先,直接在字符串末尾加反斜杠或使用转义字符添加双反斜杠都不可行

mystr='C:\numpyPacket\Program Files\python\Good\'
SyntaxError: EOL while scanning string literal
mystr='C:\\numpyPacket\\Program Files\\python\\Good\\\'
SyntaxError: EOL while scanning string literal
>>> mystr=r'C:\numpyPacket\Program Files\python\Good\'
SyntaxError: EOL while scanning string literal
>>> 

正确的操作:

字符串末尾只有一个斜杠:

>>> mystr='C:\\numpyPacket\\Program Files\\python\\Good\\'
>>> mystr
'C:\\numpyPacket\\Program Files\\python\\Good\\'
>>> print(mystr)
C:\numpyPacket\Program Files\python\Good\

字符串末尾有2个斜杠:

>>> mystr='C:\\numpyPacket\\Program Files\\python\\Good\\\\'
>>> mystr
'C:\\numpyPacket\\Program Files\\python\\Good\\\\'
>>> print(mystr)
C:\numpyPacket\Program Files\python\Good\\
>>> mystr=r'C:\numpyPacket\Program Files\python\Good\\'
>>> mystr
'C:\\numpyPacket\\Program Files\\python\\Good\\\\'
>>> print(mystr)
C:\numpyPacket\Program Files\python\Good\\