简体   繁体   English

在字符串中使用python'\\'特殊字符操作

[英]operate with python '\' special character in a string

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:例如,我的字符串是“HowAre\\youDoing”,我想要返回字符串“HowAreyouDoing”(不带字符“\\”。我的循环是:

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).在 python 中,与大多数编程语言一样,反斜杠字符用于引入特殊字符,例如\\n表示换行符或\\t表示制表符(以及更多)。

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 \\\\ :如果你在 python 中用\\y初始化一个字符串,它会自动转义它,因为\\y不是一个有效的特殊字符,python 假设你想要实际的字符\\被转义为\\\\

>>> 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 == '\\':

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM