Search code examples
pythonstringcut

Replace backslash in String with Python 3.8


I have looked up several methods to extract backslashes from a string in Python, but none of them workes for me. My String looks like the following:

s = "This is just a \ test \ string"


And i tried the following (because of several answers on stackoverflow):

s.replace('\\', "")

But this does not work. I get the following output:

print(s)
>>> "This is just a \ test \ string"

Thank you!


Solution

  • This is because string.replace does not alter the string in-place. The following should work:

    >>> s = "This is just a \ test \ string"
    >>> s = s.replace('\\', "")
    >>> s
    'This is just a  test  string'