如何在字符串中获取名称?

时间:2016-02-05 19:52:51

标签: python string python-3.x path directory

获取目录的姓氏:

str = "/folderA/folderB/folderC/folderD"
editstr = str.split("/")[-1]
print(editstr)

folderD

如何在folderD之前获取所有目录(没有最后一个斜杠)? E.g:

editstr = ???
print(editstr)

/folderA/folderB/folderC

2 个答案:

答案 0 :(得分:2)

There is a module for this.

>>> import os
>>> s = "/folderA/folderB/folderC/folderD"
>>> os.path.basename(s)
'folderD'
>>> os.path.dirname(s)
'/folderA/folderB/folderC'

答案 1 :(得分:1)

您可以使用str.rsplit()

>>> editstr = str.rsplit('/folderD', 1)[0]
>>> print(editstr)
/folderA/folderB/folderC