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
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'
You should escape the character
for c in string:
if c == '\\':
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.