[英]Remove specific section of string
Hi I have a file that contains several thousand file paths that I am looking to move to Wazhu.您好我有一个包含数千个文件路径的文件,我希望将其移至 Wazhu。 Problem is I need directories so what I have looks like
>/apples/oranges/test.ex<
What I need is >/apples/oranges<
Not sure if Regex or just using str.replace()
is better.问题是我需要目录,所以我看起来像
>/apples/oranges/test.ex<
我需要的是>/apples/oranges<
不确定是 Regex 还是仅使用str.replace()
更好。 As each line is different I would need to find the last /
and remove it as well as everything up to <
由于每一行都不同,我需要找到最后一个
/
并删除它以及直到<
Hopefully that makes sense.希望这是有道理的。
s = '>/apples/oranges/test.ex<'
s = '/'.join(s.split('/')[:-1])+'<' # Splits s by '/', remove the last object, join them together, plus a '<'
print(s)
>/apples/oranges<
You don't need regex to do this.您不需要正则表达式来执行此操作。 You can simply use: os.path.split
您可以简单地使用: os.path.split
import os
head, tail = os.path.split("/apples/oranges/test.ex")
print(head)
Output: /apples/oranges
I was stuck with the same issue, the above method solved it!我遇到了同样的问题,上面的方法解决了!
you mean you want only everything except for the last "/"?你的意思是你只想要除了最后一个“/”之外的所有东西?
import os
file = open('file.txt', 'r')
for line in file.read().splitlines():
print('/'.join(line.split('/',-1)[:-1]) + "<")
You could write你可以写
import re
s = '>/apples/oranges/test.ex<'
re.match(r'.*(?=\/)', s).group()
which returns返回
>/apples/oranges
This works because .*
is greedy, so it consumes all forward slashes up to the last one.这是有效的,因为
.*
是贪婪的,所以它消耗所有正斜杠直到最后一个。 (?=\/)
is a positive lookahead . (?=\/)
是一个积极的前瞻。 group(0)
also works. group(0)
也有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.