Convert backward slash to forward slash in python


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

11/28/2010 3:36:15 PM

Accepted Answer

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('\\', '/')

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

11/28/2010 3:24:03 PM

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow