As example from the title, I want the result:
Dir : home/tom/cat
first cut : tom/cat
second cut: /cat
last cut: /
How to do it in python?
Is this what you're looking for:
In [101]: dir = "home/tom/cat"
In [102]: dir.split('/')
Out[102]: ['home', 'tom', 'cat']
You might also want to split on os.path.sep
to be cross-platform compatible
Is this what you're looking for? Assuming that your strings look like that (ie no leading slash), you could try a generator. Note that this doesn't match your output above because I wasn't sure as to why the first pass would return tom/cat
but the second pass would return /cat
(with the slash in front). You could modify this to yield a 'default' (such as /
) when the while
loop completes if that is what you wanted. If your strings will include a leading /
, you can adjust by stripping out empty elements from your split:
In [1]: def PathSplit(s):
...: split_len = len(s.split('/'))
...: yield s
...: if split_len > 1:
...: while split_len > 1:
...: splitter = s.split('/', 1)[1]
...: yield splitter
...: s = splitter
...: split_len = len(s.split('/'))
...:
...:
In [2]: for i in PathSplit('home/tom/cat'):
...: print i
...:
...:
home/tom/cat
tom/cat
cat
In [3]: for i in PathSplit('home/tom/cat/another/long/dir'):
...: print i
...:
...:
home/tom/cat/another/long/dir
tom/cat/another/long/dir
cat/another/long/dir
another/long/dir
long/dir
dir
import os
def split_path(s):
while os.sep in s:
rv, s = s.split(os.sep, 1)
yield s
for split in split_path("home/tom/cat"):
print split
# prints
tom/cat
cat
safer way than just splitting on the '/':
In [135]: import os
In [136]: dir = '/home/tom/cat'
In [137]: os.path.basename(dir)
Out[137]: 'cat'
This cuts the first directory in your string:
dir = 'home/tom/cat'
parts = dir.split('/')
print '/'.join(parts[1:])
It splits the string into an array of dirs, then joins all but the first of them together again. Removes the first directory on each cut.
You can split and rejoin with the os module:
import os
def cutPath(path):
return os.path.join(os.path.split(path)[1:])
i might use something like this for to get the output of each step:
import os
path = "home/tom/cat"
while path:
base = os.path.basename(path)
path = path.rstrip(base)
print base
Here's a clean answer I haven't seen elsewhere:
>>> mypath="first/second/third/fourth/fifth.txt"
>>> mypath.split('/',1)
['first', 'second/third/fourth/fifth.txt']
>>> mypath.split('/',1)[1]
'second/third/fourth/fifth.txt'
Split can split a string at the first split.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.