我如何在 Python 中用“\”替换字符串列表“\\”

How i can replace in a list of strings "\\" with "\" in Python

在我的代码中,我有一个位置列表,列表的输出是这样的

['D:\Todo\VLC\Daft_Punk\One_more_time.mp4"', ...

我想用“\”替换“\\” (listcancion 是一个包含所有字符串的列表) 我尝试用此代码 remplacement = [listcancion.replace('\', '\') for listcancion in listcancion] 或此 remplacement = [listcancion.replace('\\', '\') for listcancion in listcancion] 或此 remplacement = [listcancion.replace('\', 'X') for listcancion in listcancion] listrandom = [remplacement.replace('X', '\') for remplacement in remplacement]

替换

我只需要更改字符 \ 我不能这样做 ("\Todo", "\Todo") 因为我有更多字符需要替换。

如果我能在没有进口的情况下解决,那就太好了。

这只是字符串表示的问题。

首先,您必须区分字符串的 "real" 内容及其表示形式。

一个字符串的"real"内容可能是字母、数字、标点符号等等,这使得显示起来非常容易。但是想象一下包含 a、一个换行符和一个 b 的字符串。如果你打印那个字符串,你会得到输出

a
b

这就是你所期望的。

但是为了更简洁,这个字符串的表示形式是a\nb:换行符表示为\n\作为转义字符。比较 print(a)(与 print(str(a)) 相同)和 print(repr(a)).

的输出

现在,为了不将其与包含 a\nb 的字符串混淆,"real" 中的反斜杠一个字符串具有 \ 的表示形式,而打印为 a\nb 的相同字符串具有 a\nb 的表示形式,以便与第一个示例区分开来。

如果您打印任何内容的列表,它会显示为以逗号分隔的组件表示形式列表,即使它们是字符串也是如此。

如果你这样做

for element in listcancion:
    print(element)

您会看到该字符串实际上只包含一个 \,其表示形式显示 \

(哦,顺便说一句,我不确定 [listcancion.<something> for listcancion in listcancion] 之类的东西是否按预期工作;最好使用另一个变量作为循环变量 n,例如 [element.<something> for element in listcancion]。)