1

I tried this but did not work.

import re

s = "Ex\am\ple String"
replaced = re.sub("\", "/", s)

print replaced 

Any suggestions?

Srdjan M.
  • 3,310
  • 3
  • 13
  • 34
udhkl
  • 15
  • 2

4 Answers4

3

Just use this code:

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

It replaces all the backslashes with the forward slash. The reason for the two backslashes is because you have to escape the other backslash.

Tim Lee
  • 358
  • 2
  • 8
3

Try it like this with \\\\:

import re

s = "Ex\am\ple String"
replaced = re.sub("\\\\", "/", s)

print replaced 
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

You likely aren't using enough backslashes. Backslash is often an escape character. Try commenting here using one \, then two \, you'll notice you only get one in the output here.

code version of what I just typed to show what I mean:

Backslash is often an escape character. Try commenting here using one \, 
then two \\, you'll notice you only get one in the output here.

I wrote a similar code in R for when I cut and paste file locations

fileLoc = function(){
  Rlocation = gsub( "\\\\","/",readClipboard())
  return(Rlocation)
}

Notice it required 4 backslashes.

Try the following:

s = "Ex\am\ple String"
replaced = re.sub("\\\\", "/", s)
Dick McManus
  • 739
  • 3
  • 12
  • 26
2

You have two problems: First, your string is not what you think it is, because '\a' is interpreted as an escape literal. To fix this, use a raw or regex string,

s = r"Ex\am\ple String"

Now you can do what you want using

replaced = re.sub(r"\\", "/", s)

Here, two \ are needed because re expect a single \ to be an escape character. Also, the r"\\" needs to be a raw string because Python more generally also interprets "\" as an escape character. To "escape the escape character" itself, you can do the double \ trick again, and so another way of doing it would be

replaced = re.sub("\\\\", "/", s)

Better method

Escaping and the re module aside, for simple replacements like this, you should use the str replace method,

replaced = s.replace("\\", "/")

("only" two \ needed because we are only using "bare" Python, not also re)

jmd_dk
  • 12,125
  • 9
  • 63
  • 94