1

我正在开发一个项目,以便使用 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'"]

谁能帮我?

我宁愿不进口任何东西。

4

2 回答 2

1

原始字符串只是字符串。路径可以以相同的方式使用,只要它们包含正确的字符。

>>> raw_strings = [r'Paths', r'C:\Program Files\Something']
>>> non_raw_strings = ['Paths', 'C:\\Program Files\\Something']
>>> raw_strings == non_raw_strings
True
>>> raw_strings[1]
'C:\\Program Files\\Something'
>>> print(raw_strings[1])
C:\Program Files\Something

但是,如果将反斜杠加倍使用原始字符串,则会得到不同的字符串:

>>> r'C:\Program Files\Something' == r'C:\\Program Files\\Something'
False

您可能会感到困惑的部分原因是printinglist对象将用于repr格式化列表中的项目,交互式 Python 提示符也将repr用于格式化字符串。这意味着包含单个反斜杠的字符串可能看起来像包含两个反斜杠。但不要被愚弄:

>>> one_backslash_char = '\\'
>>> len(one_backslash_char)
1
>>> one_backslash_char
'\\'
>>> print(one_backslash_char)
\
>>> list_containing_string = [one_backslash_char]
>>> print(list_containing_string)
['\\']
>>> list_containing_string[0]
'\\'
>>> print(list_containing_string[0])
\

如果您的目标是将字符串与正则表达式一起使用,并且您想将对正则表达式语法(例如\)有意义的字符转换为将正则表达式匹配相应文字的形式(例如,您有\,您想匹配\,所以string 需要包含\\),那么你想要的函数就是re.escape(string)这样做的。

于 2018-03-28T15:39:40.163 回答
0

如果我明白这一点,您想使用 匹配某个路径re.compile,但这不是它的工作原理。根据文档,你应该试试这个:

prog = re.compile(pattern)
result = prog.match(string)

在你的情况下,我会尝试

for pattern in rPaths:
    prog = re.compile(pattern)
    rPaths2 = [prog.match(string) for string in Paths]

同样,不能 100% 确定您的问题到底是什么。这有帮助吗?

于 2018-03-28T15:44:32.207 回答