我正在尝试将所有双反斜杠替换为只有一个反斜杠。我想用'class=\"highlight'替换'class=\\"highlight'。我认为python将'\\'视为一个反斜杠,将r'\\+'视为包含两个反斜杠的字符串。但当我尝试的时候
In [5]: re.sub(r'\\+', '\\', string)
sre_constants.error: bogus escape (end of line)因此,我尝试将替换字符串替换为原始字符串:
In [6]: re.sub(r'\\+', r'\\', string)
Out [6]: 'class=\\"highlight'这不是我想要的。因此,我在原始字符串中只尝试了一个反斜杠:
In [7]: re.sub(r'\\+', r'\', string)
SyntaxError: EOL while scanning string literal 发布于 2013-05-21 23:42:47
为什么不使用string.replace()
>>> s = 'some \\\\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles或者使用"raw“字符串:
>>> s = r'some \\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles因为转义字符很复杂,所以您仍然需要对它进行转义,这样它才不会转义'
发布于 2013-05-21 23:50:54
字符串中只有一个反斜杠:
>>> string = 'class=\\"highlight'
>>> print string
class=\"highlight现在让我们把另一个放进去
>>> string = 'class=\\\\"highlight'
>>> print string
class=\\"highlight然后再将其删除
>>> print re.sub('\\\\\\\\', r'\\', string)
class=\"highlight发布于 2021-08-03 08:16:20
只需使用.replace()两次!
我有以下路径:C:\\Users\\XXXXX\\Desktop\\PMI APP GIT\\pmi-app\\niton x5 test data
要将\转换为单反斜杠,我只需执行以下操作:
path_to_file = path_to_file.replace('\\','*')
path_to_file = path_to_file.replace('**', '\\')第一个操作为每个\创建**,第二个操作转义第一个斜杠,将**替换为一个\。
结果:
C:**Users**z0044wmy**Desktop**PMI APP GIT**pmi-app**GENERATED_REPORTS
C:\Users\z0044wmy\Desktop\PMI APP GIT\pmi-app\GENERATED_REPORTShttps://stackoverflow.com/questions/16673994
复制相似问题