Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要替换python3字符串中的反斜杠吗_Python_Regex_Python 3.x - Fatal编程技术网

要替换python3字符串中的反斜杠吗

要替换python3字符串中的反斜杠吗,python,regex,python-3.x,Python,Regex,Python 3.x,我有一根绳子 "abc INC\","None", "0", "test" 从这个字符串中,我想替换出现在“with a pipe |”之前的任何反斜杠。我编写了以下代码,但它实际上去掉了“”,并保留了\ import re str = "\"abc INC\\\",\"None\", \"0\", \"test\"" str = re.sub("(\\\")", "|", str) print(str) Output: |abc INC\|,|None|, |0|, |test| Desi

我有一根绳子

"abc INC\","None", "0", "test"
从这个字符串中,我想替换出现在“with a pipe |”之前的任何反斜杠。我编写了以下代码,但它实际上去掉了“”,并保留了\

import re
str = "\"abc INC\\\",\"None\", \"0\", \"test\""
str = re.sub("(\\\")", "|", str)
print(str)

Output: |abc INC\|,|None|, |0|, |test|
Desired Output: "abc INC|","None", "0", "test"
有人能指出我做错了什么吗?

您可以使用以下肯定的前瞻性断言
“\\(?=”)

尽量不要使用内置名称作为变量的名称,即
str
,以避免隐藏内置名称。

请参阅Jamie Zawinksi的。尝试仅在绝对必要时使用re。在这种情况下,它不是

string
str
(顺便说一句,变量的名称不好,因为有一个内置类型的名称)的实际内容是

为什么不

str.replace('\\"', '|"')

这将完全满足您的需求。

这必须解决您的问题:

import re
s = "\"abc INC\\\",\"None\", \"0\", \"test\""
s = re.sub(r"\\", "|", s)

另外,不要使用str作为变量名,它是一个保留关键字。

对于python正则表达式中的文本反斜杠,您需要转义两次,从而获得模式
“\\\”
“\”“
。python需要进行第一次转义,以便在字符串中实际添加反斜杠。但是正则表达式模式本身使用反斜线作为特殊字符(用于
\w
单词字符等)。各国:

特殊序列由“\”和下表中的一个字符组成。如果普通字符不在列表中,则生成的RE将与第二个字符匹配

因此模式
\“
将匹配单个
,因为
不是具有特殊含义的字符


您只能使用原始符号转义一次:
r'\\”

不懂python,但是您可以使用这个正则表达式
\\(?=”
请使用
'
来分隔python字符串。如果内部有
,则可以更清楚地看到您的字符串是什么strings@MosesKoledoye它是一个完整的字符串。阅读包含转义序列的代码。@jotasi这里是完成此任务的输出
“abc INC\\\\”、|“None”、|“0”、|“test”
@Jacquot str=“\”abc INC\\”、“None\”、“0\”、“test\”。有什么好的教程可以让我学习这个坏男孩吗?@r0xette你们可以从开始。它有很多有用的细节和一些例子:))谢谢。我没想过。我会记住“尽量只在绝对必要时使用re。”
str.replace('\\"', '|"')
import re
s = "\"abc INC\\\",\"None\", \"0\", \"test\""
s = re.sub(r"\\", "|", s)