我正在做一个项目,以便学习和开发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'"]
有人能帮我吗?在
我不想进口任何东西。在
如果我清楚地理解了这一点,您希望使用
re.compile
匹配某个路径,但这不是它的工作方式。根据documentation,您应该尝试以下操作:在你的情况下,我会尽力的
^{pr2}$再说一次,不是百分之百确定你的问题到底是什么。这有帮助吗?在
原始字符串只是字符串。只要路径中包含正确的字符,就可以使用相同的方法。在
但是,如果您将反斜杠的两倍和使用原始字符串,则会得到不同的字符串:
^{pr2}$可能让您困惑的部分原因是
print
对象的list
将使用repr
来格式化列表中的项,而交互式Python提示也将使用repr
来格式化字符串。这意味着包含一个反斜杠的字符串可能看起来像包含两个反斜杠。但不要被愚弄:如果您的目标是将字符串与正则表达式一起使用,并且您希望将对regex语法有意义的字符(例如} ,它正是这样做的。在
\
)转换为正则表达式与相应文本相匹配的形式(例如,您有\
,那么您希望匹配\
,因此字符串需要包含\\
),那么您需要的函数是^{相关问题 更多 >
编程相关推荐