在Python中处理非字符串文字中的反斜杠字符
我从 XML 元素中读取以下字符串,并将其分配给名为 filename 的变量。 我不知道如何让这一点更清楚,比如 filename = the following string,而不会让别人认为我有一个字符串文字。
\\server\data\uploads\0224.1307.Varallo.mov
当我尝试将其传递给我
os.path.basename(filename)
时,我得到以下内容
\\server\\data\\uploads\x124.1307.Varallo.mov
我尝试了 filename.replace('\\','\\\\') 但这也不起作用。 os.path.basename(filename) 然后返回以下内容。
\\\\server\\data\\uploads\\0224.1307.Varallo.mov
请注意,\0 现在没有转换为 \x,但现在它根本不处理该字符串。
我可以对我的文件名变量做些什么来使这个字符串处于正确的状态,以便 os.path.basename() 实际上会返回基本名称。我在 OSX 上,所以 uncpath 的东西不可用。
所有用 \\ 手动替换 \ 的尝试都会失败,因为 \0 在基本名称的开头被转换为 \x。
注意:这不是字符串文字,因此 r'' 不起作用。
I have the following string read from an XML elememnt, and it is assigned to a variable called filename. I don't know how to make this any clearer as saying filename = the following string, without leading someone to think that I have a string literal then.
\\server\data\uploads\0224.1307.Varallo.mov
when I try and pass this to
os.path.basename(filename)
I get the following
\\server\\data\\uploads\x124.1307.Varallo.mov
I tried filename.replace('\\','\\\\') but that doesn't work either. os.path.basename(filename) then returns the following.
\\\\server\\data\\uploads\\0224.1307.Varallo.mov
Notice that the \0 is now not being converted to \x but now it doesn't process the string at all.
what can I do to my filename variable to get this String in a proper state so that os.path.basename() will actually give me back the basename. I am on OSX so the uncpath stuff is not available.
All attempts to replace the \ with \\ manually fail because of the \0 getting converted to \x in the beginning of the basename.
NOTE: this is NOT a string literal so r'' doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们需要更多信息。变量文件名到底是什么?要回答,请使用
print repr(filename)
并将结果添加到上面的问题中。疯狂猜测
免责声明:这是一个猜测 - 尝试:
We need more information. What exactly is in the variable filename? To answer, use
print repr(filename)
and add the results to your question above.Wild guess
DISCLAIMER: This is a guess - try:
世界上所有的反对票都不会改变你做错了的事实。
os.path
用于本机路径。\\foo\bar\baz
不是 OS X 路径,而是 Windows UNC。posixpath
不具备处理 UNC 的能力;ntpath
是。All the downvoting in the world won't change the fact that you're doing it wrong.
os.path
is for native paths.\\foo\bar\baz
is not a OS X path, it's a Windows UNC.posixpath
is not equipped to handle UNCs;ntpath
is.