Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: bad escape (end of pattern) at position 0 while trying to replace to backslah

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\

like image 552
user3193813 Avatar asked May 19 '19 08:05

user3193813


1 Answers

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

print(re.sub('a','\\\\','abrakadabra'))
# \br\k\d\br\
like image 125
gregk Avatar answered Nov 08 '22 02:11

gregk