python - 使用Python将给定的相对路径添加到字符串中的另一个路径

标签 python string python-3.x

我有一个字符串,里面有一些相对路径,如下所示:

<AdditionalIncludeDirectories>..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

我只想为每个路径添加 ..\..\

我可以使用 replace 方法来做到这一点,但这里的问题是“向上步骤”的数量不固定(取决于我要替换的字符串)。

如果我尝试将 ..\ 替换为 ..\..\..\ 之类的内容,我的脚本将替换他发现的每个事件。所以我的最终结果如下 ..\..\..\..\..\..\..\..\..\..\..\..\.

那么我如何在 Python 3 中仅向此字符串中的每个路径添加 2 个“向上步骤”。

期望的结果是:

<AdditionalIncludeDirectories>..\..\..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

最佳答案

还有更好的方法,但这应该有效。

a = 'AdditionalIncludeDirectories>..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>'  
b = re.search('>(.*)<', a)## Get paths str position
paths_str = a[b.start() + 1:b.end() - 1]## paths_str
paths = paths_str.split(';')
full_paths = ['..\..\{0}'.format(path) for path in paths]## adding up dirs
full = '{0}>{1}<;{2}'.format(a[:b.start()], ';'.join(full_paths), 
a[b.end():])## Combining together.  

关于python - 使用Python将给定的相对路径添加到字符串中的另一个路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46219322/

相关文章:

python - urllib2.urlopen() 与 urllib.urlopen() - urllib2 在 urllib 工作时抛出 404!为什么?

javascript - Selenium 单击 GDPR 单击按钮

python - 碎片 find_by_xpath : using regex for element text()

java - 将 InputStream 转换为 base64 字符串

c++ - char数组声明中字符串文字周围的大括号有效吗? (例如 char s[] = {"Hello World"})

r - 将日期列转换为 'period-year'列

python - 协助/审查我的 python 3 以解决虚构的巴士座位问题

python - 获取两个指定元素之间的所有列表元素

python - 如何让文字显示5秒然后消失并显示按钮?

python - 值错误 : Item wrong length 907 instead of 2000