find and remove "\" character from string

Stefan Behnel stefan.behnel-n05pAM at web.de
Sat Sep 15 12:42:42 EDT 2007


Konstantinos Pachopoulos wrote:
> i have the following string s and the following code, which doesn't
> successfully remove the "\", but sucessfully removes the "\\".
> 
>>>> s="Sad\\asd\asd"
>>>> newS=""
>>>> for i in s:
> ...     if i!="\\":
> ...             newS=newS+i

I'm not quite sure what you're trying to achieve, but I'd use

    >>> r"\\a\\b\c".replace("\\\\", "")
    'ab\\c'

    >>> r"\\a\\b\c".replace("\\", "")
    'abc'

Note that "\\" in the source is unescaped to "\" in the string. Use r"\\" to
prevent that.

Stefan



More information about the Python-list mailing list