简体   繁体   English

Python用反斜杠替换正斜杠

[英]Python replace forward slash with back slash

I have我有

foo = '/DIR/abc'

and I want to convert it to我想把它转换成

bar = '\\MYDIR\data\abc'

So, here's what I do in Python:所以,这就是我在 Python 中所做的:

>>> foo = '/DIR/abc'
>>> bar = foo.replace(r'/DIR/',r'\\MYDIR\data\')
  File "<stdin>", line 1
    bar = foo.replace(r'/DIR/',r'\\MYDIR\data\')
                                                 ^
SyntaxError: EOL while scanning string literal

If, however, I try to escape the last backslash by entering instead bar = foo.replace(r'/DIR/',r'\\\\MYDIR\\data\\\\') , then I get this monstrosity:但是,如果我尝试通过输入bar = foo.replace(r'/DIR/',r'\\\\MYDIR\\data\\\\')来逃避最后一个反斜杠,那么我会得到这个怪物:

>>> bar2
'\\\\MYDIR\\data\\\\abc'

Help!帮助! This is driving me insane.这让我发疯。

第二个参数应该是一个字符串,而不是一个正则表达式模式:

foo.replace(r'/DIR/', '\\\\MYDIR\\data\\')

The reason you are encountering this is because of the behavior of the r"" syntax, Taking some explanation from the Python Documentation您遇到此问题的原因是r""语法的行为,从Python 文档中获取一些解释

r"\\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). r"\\"" 是由两个字符组成的有效字符串文字:一个反斜杠和一个双引号;r"\\" 不是有效的字符串文字(即使原始字符串也不能以奇数个反斜杠结尾)。具体来说,一个原始字符串不能以单个反斜杠结尾(因为反斜杠会转义后面的引号字符)。

So you will need to use a normal escaped string for the last argument.因此,您需要对最后一个参数使用普通的转义字符串。

>>> foo = "/DIR/abc"
>>> print foo.replace(r"/DIR/", "\\\\MYDIR\\data\\")
\\MYDIR\data\abc

我只是在/前面放了一个r来改变正斜杠。

inv_num = line.replace(r'/', '-')

Two problems:两个问题:

  1. A raw literal simply cannot end with a single backslash because it is interpreted as escaping the quote character.原始文字不能以单个反斜杠结尾,因为它被解释为转义引号字符。 Therefore, use a regular (non-raw) literal with escapes: '\\\\\\\\MYDIR\\\\data\\\\' .因此,使用带有转义'\\\\\\\\MYDIR\\\\data\\\\'的常规(非原始)文字: '\\\\\\\\MYDIR\\\\data\\\\'
  2. When displayed (using the repr style), strings will appear with escapes.显示时(使用repr样式),字符串将带有转义符。 Therefore, '\\\\\\\\' only has two actual backslashes.因此, '\\\\\\\\'只有两个实际的反斜杠。 So, '\\\\\\\\MYDIR\\\\data\\\\\\\\abc' is really \\\\MYDIR\\data\\\\abc .所以, '\\\\\\\\MYDIR\\\\data\\\\\\\\abc'实际上是\\\\MYDIR\\data\\\\abc

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

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