Python Forum
change backslash into slash in a path
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
change backslash into slash in a path
#1
Hi

Typically in a Windows path, I want to change the special "backslash" character to "slash" one. I was thinking re.sub substitutes all occurences but whatever I've tested so far, it fails (same result using replace()): what I'm missing?

Path = 'D:\My Directory1\bin'
NewPath = re.sub(r'(\\)', '/', Path)
print(f"New path = {NewPath}")
(of course the number of "\" can change)

leading to:
Output:
New path = D:/My Directoryin
Thanks

Paul
Reply
#2
Your problem starts with
Path = 'D:\My Directory1\bin'
Path does not contain the string "\b". "\b" is an escape sequence for the back space character, so "Directory1\bin" is really "Directoryin". The substitution of "\b" with backspace has already happened before you try to replace or substitute. Your attempts fail because there is no backslash to replace.

To fix the problem you have to fix the str. Use "\\" if you want the str to contain "\" as a character, or use raw strings.
path = r'D:\My Directory1\bin'
path = 'D:\\My Directory1\\bin'
Of possible interest "\M" is just a str with a backslash followed by "M". This is because "\M" is not a recognized escape sequence like \b, \f, \n, \o, \r, \t, \u, \x
Reply
#3
Thanks deanhystad for your answer.

I agree with you, but the goal here is to directly rewrite a path in a good format when an external user copy/paste it from Windows; I was thinking that a basic instruction ever exists (replace or re.sub / etc), and I've done tests accordingly, but all failed.

Humm I guess it'll be necessary to write my own function to do that ...

Thanks

Paul
Reply
#4
If the user enters a string containing "\" it will be a backslash, and not interpreted as an escape sequence.

These all do what you want to do
import re

path = r'D:\My Directory1\bin'
print("using replace", path.replace("\\", "/"))
print("using replace with raw string", path.replace(r"\ "[0], "/"))
print("using regex", re.sub('\\\\', '/', path))
Output:
using replace D:/My Directory1/bin using replace with raw string D:/My Directory1/bin using regex D:/My Directory1/bin
Notice the funny code needed to get around Python not allowing any kind of string literal (even a raw string) to end with a single backslash.
But if you are using this to get a file path from a user, I would use the pathlib. This code lets me use "/" or "\".
import pathlib

path = pathlib.Path(input("Filename "))
print(path)
Reply
#5
I played with "replace()" but it didn't worked wheareas your snippets are fine; I don't know what I did ? Huh

Thanks for you support
Reply
#6
(Jul-21-2022, 11:41 AM)paul18fr Wrote: I played with "replace()" but it didn't worked wheareas your snippets are fine; I don't know what I did ? Huh

Thanks for you support
Your example did not work because the \b in Path was a backspace. There was not a backslash to replace. If you tried replace() on a string entered using input() it should have worked (assuming you used "\\" as the target string).
Reply
#7
Yes I understand, but there's also another difference: you've add the "r" in front of the string to declare a "regular expression" whereas in my case I'm using a variale: how can I use a variable or how can I declare the variable as a regular expression?

path = 'D:\My Directory1\bin'
Var = r''+ path   #Var = r'' + str(path)
print("using replace", Var.replace('\\', '/'))
print("using replace with raw string", path.replace(r"\ "[0], "/"))
print("using regex", re.sub('\\\\', '/', path))
(obviously it does not work because of \b as it has ever been sugested)
Reply
#8
There is no need to replace "\" with "/". str objects never contain escape sequences. A backslash in a string is just a backslash. Escape sequences only exist in string literals, strings that are hardcoded in your program.

This program's problem happened when the Python code is compiled.
path = "D:\My Directory1\bin"  # Contains escape sequence \b
print(path, path.replace("\b", r"\b"))
Output:
D:\My Directoryin D:\My Directory1\bin
When Python compiled "Path = 'D:\My Directory1\bin'" it converted the "\b" to a backspace character (ASCII control character BS). The resulting string was 'D:\My Directory1<BS>in' where <BS> is the backspace character. At no point does the path str include a "\b" escape sequence, so it would be impossible to replace the "\b" with "/b". The path str does include a backspace character and you can replace that character a "\b" string. There is no reason to do this, but it is possible.

Thing learned here:
1. You cannot replace escape sequences in a str object because str objects do not contain escape sequences.
2. Escape sequences are converted to characters when Python compiles your program.
3. You don't have to worry about backslashes in input strings. In a str a backslash is just a backslash.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,225 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  How could i change the python interpreter path of os.system() 12019202386 2 2,591 Sep-02-2020, 06:58 AM
Last Post: DeaD_EyE
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,500 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  Deny backslash using regex JohnnyCoffee 1 1,703 Mar-18-2020, 10:21 PM
Last Post: snippsat
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,781 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908
  converting backslash codes Skaperen 4 5,454 Apr-21-2018, 04:07 AM
Last Post: Skaperen
  Reading and writing Windows filepath without treating backslash as escape character Dangthrimble 3 3,549 Dec-18-2017, 06:18 PM
Last Post: DeaD_EyE
  [split] Single slash syntax in file path aogata 3 4,570 Aug-09-2017, 04:50 PM
Last Post: snippsat
  Replace Single Backslash with Double Backslash in python saswatidas437 2 33,359 Mar-19-2017, 10:48 AM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020