9

I need to replace single backslash in my string. I'm trying to perform '\' but it gives with me double backslash. When i'm performing '\' it throw error bad escape (end of pattern) at position 0

string = 'abrakadabra'
string.replace('a','\\')
#or
re.sub('a','\\','abrakadabra')

In [47]: string.replace('a','\'')
Out[47]: "'br'k'd'br'"

In [48]: string.replace('a','\')
 File "<ipython-input-48-e884682860ae>", line 1
string.replace('a','\')
                       ^

SyntaxError: EOL while scanning string literal

In [49]: string.replace('a','\\')
Out[49]: '\\br\\k\\d\\br\\'

In [50]: 

expecting for result: \br\k\d\br\

user3193813
  • 147
  • 1
  • 1
  • 8

1 Answers1

11

You should use '\\\\', then you will pass '\\' to re, which is just one escaped backslash.

print(re.sub('a','\\\\','abrakadabra'))
# \br\k\d\br\
petezurich
  • 9,280
  • 9
  • 43
  • 57
gregk
  • 179
  • 5