python - 如何获取字符串中的名字?

标签 python string python-3.x path directory

获取目录的姓氏:

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

folderD

如何获取 folderD 之前的所有目录(没有最后一个斜杠)?例如:

editstr = ???
print(editstr)

/folderA/folderB/folderC

最佳答案

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'

关于python - 如何获取字符串中的名字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232392/

相关文章:

python - 使用 Python3 C API 添加到内置函数

C++ string.replace 生成 "No matching function for call"错误

c - 字符串长度错误

python - Python 中的类与类型

python-3.x - 用线连接 mask 点

python - 在定义模型之前先将ForeignKey定义到该模型

Python Tkinter 坐标函数不会在循环内移动 Canvas 对象

python - sys.exit() 不会终止我的程序

python - 检查里面的for循环没有执行

c - 字符串函数: insert - self implemented via a copy function