Replace '\' character in python
python, string
Solution
You need to escape it with another backslash:
x.replace('\\', '-')
Backslashes are special, in that they are used to introduce non-printing characters like newlines into a string.
It's also how you add a `'` character to a `'`-quoted string, which is what Python thinks you were trying to do. It sees `\'` and interprets as a literal quote within the string, rather than letting the `'` end the string. Then it gets to the end of the string and finds `EOL` ("end of line") before the end of the string.
To introduce a real backslash, you need to double it. You can see that Python itself did this when printing the representation of your initial string here:
>>> x
'hello\\world'
Note the double backslash.
You ought to use a double backslash when specifying your string in the first place. The reason that doesn't need it is that `\w` is not a special character, so it gets interpreted as a literal backslash and a `w`. Had you said `'Hello\now'` you would have a string with a newline in it.
You could have also marked the string as a "raw" string by prepending it with `r` as in `r'hello\world'`. This marks the string as not being eligible for any substitutions of special characters.
Problem
I don't know why i can't find it, but i wanted to replace the special character `'\'` in python. I have a String within i have `'\'` characters but i confident find the solution, to replace it with '-'. This is what happening while i am trying to replace, ``` >>> x = 'hello\world' >>> x 'hello\\world' >>> x.replace('\', '-') File "<stdin>", line 1 x.replace('\', '-') SyntaxError: EOL while scanning string literal ``` EDIT: Do try this it in the eclipse IDLE ``` x = 'hello\world' print x x.replace('\\', '-') print x ``` Output: ``` hello\world hello\world ```