转换包含原始字符串的字符串列表中的列表

2024-09-27 00:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个项目,以便学习和开发python3的代码功能。在这个项目中,我需要带路径的原始字符串。在

示例:

rPaths = [r"Path to the app", r"C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe", r"F:\\VLC\\vlc.exe"]

我还需要从另一个仅包含普通列表的列表中实现:

^{pr2}$

为了达到这个目的,我尝试了以下方法:

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'"]

有人能帮我吗?在

我不想进口任何东西。在


Tags: thetopathappfilesprogramexemp3
2条回答

如果我清楚地理解了这一点,您希望使用re.compile匹配某个路径,但这不是它的工作方式。根据documentation,您应该尝试以下操作:

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

在你的情况下,我会尽力的

^{pr2}$

再说一次,不是百分之百确定你的问题到底是什么。这有帮助吗?在

原始字符串只是字符串。只要路径中包含正确的字符,就可以使用相同的方法。在

>>> 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

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

^{pr2}$

可能让您困惑的部分原因是print对象的list将使用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])
\

如果您的目标是将字符串与正则表达式一起使用,并且您希望将对regex语法有意义的字符(例如\)转换为正则表达式与相应文本相匹配的形式(例如,您有\,那么您希望匹配\,因此字符串需要包含\\),那么您需要的函数是^{},它正是这样做的。在

相关问题 更多 >

    热门问题