1

I am trying to iterate in a string and find a character on it and delete it. For example, my string is "HowAre\youDoing" and I want the string "HowAreyouDoing" back (without the character '\'. My Loop is:

for c in string:
     if c == '\':

The Point is that '\' is a Special character and it doesn´t allow me to do it in this way. Does anybody knows how can I proceed? thanks

Pablo
  • 45
  • 7
  • 3
    Possible duplicate of [How to print backslash with Python?](http://stackoverflow.com/questions/19095796/how-to-print-backslash-with-python) – Biffen Nov 11 '15 at 12:34
  • Just duplicate the backslash: '\\' the first one anulate the special function of the second. – Josete Manu Nov 11 '15 at 13:11

2 Answers2

1

In python, as in most programing languages, the backslash character is used to introduce a special character, like \n for newline or \t for tab (and several more).

If you initialize a string in python with \y, it will escape it automatically, since \y is not a valid special character and python assumes that you want the actual character \ which is escaped to \\:

>>> s = "HowAre\youDoing" 
>>> s
'HowAre\\youDoing'

So, to replace it in your case, just do

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

If you'd like to replace special characters like the aforementioned, you would need to specify the respective special character with an unescaped "\":

>>> s = "HowAre\nyouDoing" 
>>> s
'HowAre\nyouDoing'
>>> s.replace("\n", "")
'HowAreyouDoing'
Richard Neumann
  • 2,986
  • 2
  • 25
  • 50
0

You should escape the character

for c in string:
     if c == '\\':
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69