how to replace back slash character with empty string in python
The error is because you did not add a escape character to your '\'
, you should give \\
for backslash (\)
In [147]: foo = "a\c\d" # example string with backslashes
In [148]: foo
Out[148]: 'a\\c\\d'
In [149]: foo.replace('\\', " ")
Out[149]: 'a c d'
In [150]: foo.replace('\\', "")
Out[150]: 'acd'
We need to specify that we want to replace a string that contains a single backslash. We cannot write that as "\"
, because the backslash is escaping the intended closing double-quote. We also cannot use a raw string literal for this: r"\"
does not work.
Instead, we simply escape the backslash using another backslash:
result = string.replace("\\","")