Python String Replace - "\" by "/"

I am trying to replace a string here in Python.

This is my Input -

MyString = \\ServerA\DriveB\5.FolderC\A.TXT

I want my output to be like this

OutputString = //ServerA/DriveB/5.FolderC/A.TXT

I tried the replace method it didn't work. Is there a function that can convert it ? Kindly help me with this.

The Code tried,

MyString = '\\ServerA\DriveB\5.FolderC\A.TXT'
Output_String = MyString.replace('\', '//')
print(Output_String)

SyntaxError: EOL while scanning string literal

Upvotes: 9

Views: 42286

Answers (1)

Bill the Lizard
Bill the Lizard

Reputation: 405745

replace should work.

my_string = r'\\ServerA\DriveB\5.FolderC\A.TXT'
my_string = my_string.replace('\\', '/')

Two things that commonly go wrong:

  1. If you're not assigning back to a variable.
  2. If you're not escaping the \.

Also, note that I'm using a raw string (using an r prefix) to make sure characters aren't escaped in the original string.

Upvotes: 13

Related Questions