Convert backslash to scroll in python

Hi I read articles related to going backward into slashes. But sol should have used an unprocessed string.

But the problem in my case is:

I get a dynamic variable path Var = 'C: \ dummy_folder \ a.txt' In this case, I need to convert it to oblique strings. But due to '\ a', I cannot convert to slashes

How to convert it? OR How do I change this string to a raw string so that I can change it to a forward slash

+6
python ruby path
source share
5 answers

Do not do this. Just use os.path and let it handle everything. You must not explicitly specify a forward or backslash.

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

But then again, no need. Just use os.path and be happy!

+12
source share

There is also os.path.normpath (), which converts backslashes and slashes depending on the local OS. For more information on usage, see here . You would use it like this:

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

Handling paths as simple strings can lead to problems; even if the path you are processing is user or may be unpredictable.

Different operating systems have a different way to express the path to a given file, and each modern programming language has its own methods for processing paths and links to file systems. Of course, Python and Ruby have this:

If you really need to handle strings:

  • Python: string.replace
  • Ruby: string.gsub
+2
source share

Raw strings are for string literals (written directly in the source file), which seems not to be here. In any case, forward slashes are not special characters - they can be embedded in a regular string without any problems. These are backslashes, which usually have a different meaning in the string, and must be escaped so that they are interpreted as literal backslashes.

To replace the backslash with a slash:

 # Python: string = r'C:\dummy_folder\a.txt' string = string.replace('\\', '/') # Ruby: string = 'C:\\dummy_folder\\a.txt' string = string.gsub('\\', '/') 
+1
source share
 >>> 'C:\\dummy_folder\\a.txt'.replace('\\', '/') 'C:/dummy_folder/a.txt' 

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

0
source share

All Articles