在python中将反斜杠转换为正斜杠
你好 我读过有关将向后斜杠转换为正斜杠的文章。 但 sol 是使用原始字符串。
但我的情况的问题是:
我将动态获取变量的文件路径 var='C:\dummy_folder\a.txt' 在这种情况下,我需要将其转换为正斜杠。 但由于 '\a',我无法转换为正斜杠,
如何转换它?或者我应该如何将此字符串更改为原始字符串,以便我可以将其更改为正斜杠
Hi
I have read articles related converting backward to forward slashes.
But sol was to use raw string.
But Problem in my case is :
I will get file path dynamically to a variable
var='C:\dummy_folder\a.txt'
In this case i need to convert it to Forward slashes.
But due to '\a',i am not able to convert to forward slashes
How to i convert it? OR How should i change this string to raw string so that i can change it to forward slash
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不要这样做。只需使用 os.path 并让它处理一切。您不应显式设置正斜杠或反斜杠。
但再说一遍,不要。只需使用 os.path 就可以开心了!
Don't do this. Just use os.path and let it handle everything. You should not explicitly set the forward or backward slashes.
But again, don't. Just use os.path and be happy!
还有os.path.normpath(),它根据本地操作系统转换反斜杠和斜杠。请参阅此处了解详细的使用信息。你可以这样使用它:
There is also os.path.normpath(), which converts backslashes and slashes depending on the local OS. Please see here for detailed usage info. You would use it this way:
将路径仅作为字符串处理可能会给您带来麻烦。如果您正在处理的路径是用户输入或可能以不可预测的方式变化,则更是如此。
不同的操作系统有不同的方式来表达给定文件的路径,并且每种现代编程语言都有自己的方法来处理路径和文件系统引用。 Python 和 Ruby 肯定有它:
如果你确实需要处理字符串:
Handling paths as a mere string could put you into troubles.; even more if the path you are handling is an user input or may vary in unpredictable ways.
Different OS have different way to express the path of a given file, and every modern programming language has own methods to handle paths and file system references. Surely Python and Ruby have it:
If you really need to handle strings:
原始字符串用于字符串文字(直接写在源文件中),这里似乎不是这种情况。无论如何,正斜杠都不是特殊字符——它们可以毫无问题地嵌入到常规字符串中。反斜杠通常在字符串中具有其他含义,需要“转义”,以便将它们解释为文字反斜杠。
要将反斜杠替换为正斜杠:
Raw strings are for string literals (written directly in the source file), which doesn't seem to be the case here. In any case, forward slashes are not special characters -- they can be embedded in a regular string without problems. It's backslashes that normally have other meaning in a string, and need to be "escaped" so that they get interpreted as literal backslashes.
To replace backslashes with forward slashes:
在字符串文字中,您需要转义
\
字符。In a string literal, you need to escape the
\
character.