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
#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


Messages In This Thread
change backslash into slash in a path - by paul18fr - Jul-21-2022, 08:50 AM
RE: change backslash into slash in a path - by deanhystad - Jul-21-2022, 04:26 PM

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