Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert backward slash to forward slash in python

Tags:

python

path

ruby

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

like image 978
abhishek Avatar asked Nov 28 '10 15:11

abhishek


People also ask

How do you change backward slash to forward slash?

By default the <Leader> key is backslash, and <Bslash> is a way to refer to a backslash in a mapping, so by default these commands map \/ and \\ respectively. Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.

How do you change the backward slash in Python?

We can use the replace() function to replace the backslashes in a string with another character. To replace all backslashes in a string, we can use the replace() function as shown in the following Python code.

How do you forward a slash in Python?

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash.

How do I remove a backward slash from a string in Python?

Using replace() Function to Remove Backslash from String in Python. The replace() can be utilized to remove an escape sequence or just a backslash in Python by simply substituting it with space in Python.


2 Answers

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'
like image 43
hopia Avatar answered Oct 18 '22 05:10

hopia


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!

like image 179
user225312 Avatar answered Oct 18 '22 06:10

user225312