Convert backward slash to forward slash in python

好久不见. 提交于 2019-12-18 13:28:57

问题


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


回答1:


Don't do this. Just use os.path and let it handle everything. You should not explicitly set the forward or backward slashes.

>>> var=r'C:\dummy_folder\a.txt'
>>> var.replace('\\', '/')
'C:/dummy_folder/a.txt'

But again, don't. Just use os.path and be happy!




回答2:


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:

>>> string = r'C:/dummy_folder/a.txt'
>>> os.path.normpath(string)
'C:\dummy_folder\a.txt'



回答3:


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:

  • Python: os.path
  • Ruby: File and FileUtils

If you really need to handle strings:

  • Python: string.replace
  • Ruby : string.gsub



回答4:


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:

# Python:
string = r'C:\dummy_folder\a.txt'
string = string.replace('\\', '/')

# Ruby:
string = 'C:\\dummy_folder\\a.txt'
string = string.gsub('\\', '/')



回答5:


>>> 'C:\\dummy_folder\\a.txt'.replace('\\', '/')
'C:/dummy_folder/a.txt'

In a string literal, you need to escape the \ character.



来源:https://stackoverflow.com/questions/4297450/convert-backward-slash-to-forward-slash-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!