python用双反斜杠替换单反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17327202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:54:50  来源:igfitidea点击:

python replace single backslash with double backslash

pythonstringreplacebackslash

提问by Josh Wood

In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code:

在python中,我试图用双反斜杠(“\”)替换单个反斜杠(“\”)。我有以下代码:

directory = string.replace("C:\Users\Josh\Desktop130216", "\", "\")

However, this gives an error message saying it doesn't like the double backslash. Can anyone help?

但是,这会给出一条错误消息,指出它不喜欢双反斜杠。任何人都可以帮忙吗?

采纳答案by Ashwini Chaudhary

No need to use str.replaceor string.replacehere, just convert that string to a raw string:

无需使用str.replacestring.replace在这里,只需将该字符串转换为原始字符串:

>>> strs = r"C:\Users\Josh\Desktop130216"
           ^
           |
       notice the 'r'

Below is the reprversion of the above string, that's why you're seeing \\here. But, in fact the actual string contains just '\'not \\.

以下是repr上述字符串的版本,这就是您在\\这里看到的原因。但是,实际上实际的字符串只包含'\'not \\

>>> strs
'C:\Users\Josh\Desktop\20130216'

>>> s = r"f\o"
>>> s            #repr representation
'f\o'
>>> len(s)   #length is 3, as there's only one `'\'`
3

But when you're going to print this string you'll not get '\\'in the output.

但是当你要打印这个字符串时,你不会得到'\\'输出。

>>> print strs
C:\Users\Josh\Desktop130216

If you want the string to show '\\'during printthen use str.replace:

如果您希望字符串显示'\\'print然后使用str.replace

>>> new_strs = strs.replace('\','\\')
>>> print new_strs
C:\Users\Josh\Desktop\20130216

reprversion will now show \\\\:

repr版本现在将显示\\\\

>>> new_strs
'C:\\Users\\Josh\\Desktop\\20130216'

回答by alexpinho98

Use escape characters: "full\\path\\here", "\\"and "\\\\"

使用转义字符:"full\\path\\here","\\""\\\\"

回答by rocker_raj

Use:

用:

string.replace(r"C:\Users\Josh\Desktop130216", "\", "\")

Escape the \character.

逃离\角色。

回答by A STEFANI

Maybe a syntax error in your case, you may change the line to:

您的情况可能存在语法错误,您可以将该行更改为:

directory = str(r"C:\Users\Josh\Desktop130216").replace('\','\\')

which give you the right following output:

这为您提供了正确的以下输出:

C:\Users\Josh\Desktop\20130216

回答by CAB

Given the source string, manipulation with os.pathmight make more sense, but here's a string solution;

鉴于源字符串,使用os.path操作可能更有意义,但这里有一个字符串解决方案;

>>> s=r"C:\Users\Josh\Desktop\20130216"
>>> '\\'.join(filter(bool, s.split('\')))
'C:\\Users\\Josh\\Desktop\\20130216'

Note that splittreats the \\in the source string as a delimited empty string. Using filtergets rid of those empty strings so joinwon't double the already doubled backslashes. Unfortunately, if you have 3 or more, they get reduced to doubled backslashes, but I don't think that hurts you in a windows path expression.

请注意,split\\源字符串中的 视为分隔的空字符串。Usingfilter摆脱了那些空字符串,因此join不会使已经加倍的反斜杠加倍。不幸的是,如果您有 3 个或更多,它们会减少为双倍反斜杠,但我认为这不会在 Windows 路径表达式中伤害您。

回答by abacles

The backslash indicates a special escape character. Therefore, directory = path_to_directory.replace("\", "\\")would cause Python to think that the first argument to replace didn't end until the starting quotation of the second argument since it understood the ending quotation as an escape character.

反斜杠表示特殊的转义字符。因此,directory = path_to_directory.replace("\", "\\")会导致 Python 认为要替换的第一个参数直到第二个参数的起始引用才结束,因为它将结束引用理解为转义字符。

directory=path_to_directory.replace("\","\\")

回答by Rewanth Cool

Let me make it simple and clear. Lets use the re module in python to escape the special characters.

让我说得简单明了。让我们使用 python 中的 re 模块来转义特殊字符。

Python script :

Python脚本:

import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)

Output :

输出 :

C:\Users\Josh\Desktop
C:\Users\Josh\Desktop

Explanation :

解释 :

Now observe that re.escapefunction on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.

现在观察转义给定字符串中特殊字符的re.escape函数,我们能够在每个反斜杠之前添加另一个反斜杠,最后输出结果为双反斜杠,即所需的输出。

Hope this helps you.

希望这对你有帮助。

回答by RFV5s

In python \(backslash) is used as an escape character. What this means that in places where you wish to insert a special character (such as newline), you would use the backslash and another character (\nfor newline)

在python中\(反斜杠)用作转义字符。这意味着在您希望插入特殊字符(例如换行符)的地方,您将使用反斜杠和另一个字符(\n用于换行符)

With your example string you would notice that when you put "C:\Users\Josh\Desktop\20130216"in the repl you will get "C:\\Users\\Josh\\Desktop\x8130216". This is because \2has a special meaning in a python string. If you wish to specify \then you need to put two \\in your string.

使用您的示例字符串,您会注意到,当您放入"C:\Users\Josh\Desktop\20130216"repl 时,您将获得"C:\\Users\\Josh\\Desktop\x8130216". 这是因为\2在 python 字符串中具有特殊含义。如果你想指定,\那么你需要\\在你的字符串中放两个。

"C:\\Users\\Josh\\Desktop\\28130216"

"C:\\Users\\Josh\\Desktop\\28130216"

The other option is to notify python that your entire string must NOT use \as an escape character by pre-pending the string with r

另一种选择是通过在字符串\前面加上r

r"C:\Users\Josh\Desktop\20130216"

r"C:\Users\Josh\Desktop\20130216"

This is a "raw" string, and very useful in situations where you need to use lots of backslashes such as with regular expression strings.

这是一个“原始”字符串,在需要使用大量反斜杠(例如正则表达式字符串)的情况下非常有用。

In case you still wish to replace that single \with \\you would then use:

如果您仍然希望\\\您替换该单曲,则可以使用:

directory = string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\\\")

directory = string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\\\")

Noticethat I am not using r'in the last two strings above. This is because, when you use the r'form of strings you cannot end that string with a single \

请注意,我没有r'在上面的最后两个字符串中使用。这是因为,当您使用r'字符串的形式时,您不能以单个字符串结尾\

Why can't Python's raw string literals end with a single backslash?

为什么 Python 的原始字符串文字不能以单个反斜杠结尾?

https://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-are-escape-characters/

https://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-are-escape-characters/

回答by AHRG

You could use

你可以用

os.path.abspath(path_with_backlash)

it returns the path with \

它返回路径 \