-1

I want to use a path in python but python doesn't understand usual path with a "\". So I decided to fix it with the method ".replace" and "/". The problem is that when I use the method ".replace", it doesn't read "\" as a character... How do do it ? If I can improve this question by any way, let me know !

raw_path=(str(input("please write down the exact path")))+"/"
raw_path.replace("\","/")
O'Schell
  • 29
  • 8
  • 2
    Classic XY problem. Just use a raw string literal (`r'C:\now\backslash\can\be\used'`) – DeepSpace Jan 28 '20 at 13:38
  • Do you have an exemple? I don't really fully understand ? Thanks for your fast answer – O'Schell Jan 28 '20 at 13:39
  • Thanks @DeepSpace !! Works perfectly! – O'Schell Jan 28 '20 at 13:46
  • 1
    For reading `\ ` as a character, you need to escape it, `'\\'`. DeepSpace's fix is the 99% solution, but if a string ever does need to end with a backslash it won't work (because the only character `\ ` escapes in a raw string is the quote character itself, so it can't actually end with a backslash). – ShadowRanger Jan 28 '20 at 13:48

2 Answers2

0

Paths in python work best if you use '\\' instead of '\' or '/'

eg.

C:\\Users\\Bob\\Desktop

So for your case, you can use:

raw_path = raw_path.replace('\\', '\\\\')

or

raw_path = raw_path.replace('/', '\\\\')

if the text you get has '/' instead of '\'

0

At the end, I've used the solution of DeepSpace for another part of my code and instead used the solution of ShadowRanger. The code that I use now is:

raw_path=(str(input("please write down the exact path")))+"/"
raw_path.replace("\\","/")
O'Schell
  • 29
  • 8