2

I have

path = "/Users/xx/datasets/yyy/DefinedTS\Training\00000"

I just want to replace the '\' escape character with the '/'. I have tried:

path.replace("/","\")

But I got the error : EOL while scanning string literal

I also tried regex, writing my own function, trying to convert to ascii and replacing, but everything seems to reflect the same problem.

EDIT: I meant I tried

path.replace("\","/")

Thanks to UncleZeiv for pointing it out.

rmm
  • 55
  • 1
  • 8
  • take a look at this, it may help : https://stackoverflow.com/a/5141611/5464805. Actually "EOL" means "End of Line". Not an expert in python, but it could have something to do with the `\n`, i.e. end of line, which contains a `\\` – Olympiloutre Jun 13 '19 at 00:33
  • 1
    Yes, that was the issue. I resolved it using the answer I accepted below :) thank you – rmm Jun 13 '19 at 00:39

3 Answers3

1

Since \ is a special character it needs to be escaped with another \

path = path.replace("/","\\")

LuckyZakary
  • 1,171
  • 1
  • 7
  • 19
1

There are a number of problems:

  • The syntax of your path.replace line is incorrect. \ is an escape character and as such it needs to be escaped by prepending another \.
  • path.replace works the other way around: first the thing you want to substitute, then the thing you want to substitute it with.
  • Your string doesn't contain all of the backslashes anymore, because they have been interpreted as ... escape characters. You need to create a "raw" string.

Putting it all together:

path = r"/Users/xx/datasets/yyy/DefinedTS\Training\00000"
path = path.replace("\\", "/")
print(path)
UncleZeiv
  • 18,272
  • 7
  • 49
  • 77
  • 1
    Thank you. This worked. One more thing though: .replace is not an in-place operation so I will have to do assign it to a new variable. – rmm Jun 13 '19 at 00:34
0

[Edited]

After seeing UncleZeiv answer, I agree that you need to make it a raw string before replacing it with the backslash. So it should be:

path = r"/Users/xx/datasets/yyy/DefinedTS\Training\00000"
path = path.replace("/","\\")
Jethro Sandoval
  • 266
  • 1
  • 7