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\
You should use '\\\\'
, then you will pass '\\'
to re, which is just one escaped backsalsh.
print(re.sub('a','\\\\','abrakadabra'))
# \br\k\d\br\
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With