【发布时间】:2018-09-07 09:01:56
【问题描述】:
我正在做一个项目,以便学习和开发我的 Python 3 代码功能。在这个项目中,我需要带有路径的原始字符串。
示例:
rPaths = [r"Path to the app", r"C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe", r"F:\\VLC\\vlc.exe"]
我还需要从另一个仅包含普通列表的列表中实现这一点:
Paths = ["Path to the app", "C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe", "F:\\VLC\\vlc.exe"]
为了实现这一点,我尝试了以下方法:
rPaths1 = "%r"%Paths
rPaths2 = [re.compile(p) for p in Paths]
rPaths3 = ["%r"%p for p in Paths]
结果不理想:
>>>print(Paths)
['Path to the app', 'C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe', 'F:\\VLC\\vlc.exe']
>>>print(rPaths)
['Path to the app', 'C:\\\\Program Files (x86)\\\\MAGIX\\\\MP3 deluxe 19\\\\MP3deluxe.exe', 'F:\\\\VLC\\\\vlc.exe']
>>>print(rPaths1)
['Path to the app', 'C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe', 'F:\\VLC\\vlc.exe']
>>>print(rPaths2)
[re.compile('Path to the app'), re.compile('C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe'), re.compile('F:\\VLC\\vlc.exe')]
>>>print(rPaths3)
["'Path to the app'", "'C:\\\\Program Files (x86)\\\\MAGIX\\\\MP3 deluxe 19\\\\MP3deluxe.exe'", "'F:\\\\VLC\\\\vlc.exe'"]
谁能帮帮我?
我不想导入任何东西。
【问题讨论】:
-
请注意,原始字符串仅存在于源代码中。程序执行后,原始字符串就是字符串。原始字符串只是在 Python 文件中编写包含反斜杠的字符串的一种更简单的方法,而不是另一种字符串。请注意,打印字符串列表将打印列表中字符串的
repr,而打印字符串本身将打印str,如果字符串包含文字反斜杠,则可能会有所不同。 -
'原始字符串'一旦被评估,就只是字符串。没有特殊对象是原始字符串。不需要进一步的“转换”。您遇到的问题是您在原始字符串中使用了反斜杠转义
\\。使用原始字符串时,\\被视为文字。然后,转义版本(如repr所示)看起来像\\\\-- -
我知道它们的解释方式相同。我可以轻松地将所有 \\ 更改为 \\\\。但是,这不是目标。这是将字符串列表转换为包含被解释为原始字符串的字符串的列表,这样我(也不是用户)必须将 \\ 更改为 \\\\。手动或在代码内部。 @sytech
-
我不明白你想要获得什么。你能提供一个minimal reproducible example
-
@Pitto 我会试试的。提供了一个列表 'list = ["\a", "\b", "\c"]' 我正在尝试使用这样的代码来创建另一个具有相同元素的列表,但将它们解释为原始字符串 'rlist = [r "\a", r"\b", "\c"]' 这篇文章展示了一些我尝试过但没有成功实现目标的方法。将\更改为\\可以解决。然而,这不是故意的。
标签: python python-3.x list rawstring