各位高手请看看怎么规避 Python2 中诡异的字符转义?

2016-12-04 18:57:43 +08:00
 vtoexsir

pth='D:\mytemp\lunwenfcache\convert\20160907' #该路径明明存在
print os.path.isdir(pth) #=>False #但这里却提示该路径不存在?
后来,发现实际上 pth 字符串当中,'\201'实际上被转义了,所以第二句代码就返回 False.
如果这样定义 pth 就不会出错:
pth=r'D:\mytemp\lunwenfcache\convert\20160907'
或者这样定义也不会出错:
pth='D:\mytemp\lunwenfcache\convert\20160907'
然而,在使用 python 的过程中,类似这样的字符串被悄悄转义的情况,表面上看起来似乎难以发觉.
不知高手有什么好的经验? 多谢您的回复!

3418 次点击
所在节点    Python
17 条回复
thekoc
2016-12-04 19:10:46 +08:00
字符串里用反斜杠就会被转义,如果完全不想被转义就用三个引号。另外可以用 os.path.join 函数来构造地址
imn1
2016-12-04 19:25:32 +08:00
我只知道 py3 写成这样 D:/mytemp/lunwenfcache/convert/20160907 也行
不确定的最好用三引号
freestyle
2016-12-04 19:33:41 +08:00
路径请用 / 无论 windows 还是 linux/macos 都支持
anonymalias
2016-12-04 19:56:13 +08:00
可以加上个 r 、含义是: raw ,原始字符串,例如: pth= r'D:\mytemp\lunwenfcache\convert\20160907'
正如楼上所说,路径要用正斜线, windows 也是支持的, windows 当初在 dos 时代用反斜线就是一大败笔。。。
aristotll
2016-12-04 20:00:21 +08:00
还可以考虑使用平台无关的 pathsep `os.path.sep`
binux
2016-12-04 20:05:56 +08:00
这是你不会编程的原因,这个锅 Python2 不背。
cabbage
2016-12-04 20:19:26 +08:00
Python2 普通字符串加 r 我是养成习惯的~
omg21
2016-12-04 20:40:51 +08:00
@anonymalias 可以加上个 r 、含义是: raw ,原始字符串,例如: pth= r'D:\mytemp\lunwenfcache\convert\20160907'

如果 D:\mytemp\lunwenfcache\convert\20160907 是自动获取的怎么加 r ?
Geoion
2016-12-04 21:21:41 +08:00
os.path.join 在写路径的时候确实可以规避很多问题
kaneg
2016-12-04 21:28:36 +08:00
除了楼上各位的建议外,请用一款合适的 IDE ,这类低级错误都会给你提示的
anonymalias
2016-12-04 21:36:00 +08:00
@omg21 源是错的,没法加,
terence4444
2016-12-04 21:43:38 +08:00
我是这么写的,纯粹瞎搞:"D:\\mytemp\\lunwenfcache\\convert\\20160907"
aaronzjw
2016-12-04 23:25:39 +08:00
不要为了偷懒而不写 os.path.join()
vtoexsir
2016-12-05 10:16:23 +08:00
@thekoc 三引号包裹的字符串,如果包含\,也是会被转义的:
pth='D:\mytemp\lunwenfcache\convert\20160907'
pth_3='''D:\mytemp\lunwenfcache\convert\20160907'''
print pth==pth_3 #=>True
print os.path.isdir(pth_3) #=>False
aliipay
2016-12-05 12:50:35 +08:00
@binux 同意, pth 的缩写也是醉人
rogerchen
2016-12-05 18:12:53 +08:00
@omg21 你拿不到你说的形式,要么就是被转义了,要么就是对的。
ryd994
2016-12-05 22:33:11 +08:00
@omg21 只有字面量才被转义,为了能在源码里写进不可打印字符
内存里的数据没有转义,就是数据而已嘛

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/325226

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX