python - python中有对应 "\"的函数吗?

标签 python string python-2.7 path

我想使用“\”作为运算符实现文件路径的串联,重新定义相应的函数(如果有的话)。

例如:

path1 = '\home'
path2 = 'codes'

codepath = path1 \ path2

因此,在方法的重定义中在 path1 和 path2 之间添加 str "\",我应该断言 codepath = '\home\codes'

最佳答案

pathlib模块支持 / 用于连接路径对象。

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

作为如何使用 __div__ 的示例,这里有一个扩展 str 的简单类。只要至少一个参数是 MyPath 的一个实例,它就应该可以工作(即,它不适用于两个纯字符串)。

class MyPath(str):
    def __div__(self, other):
        assert isinstance(other, str)
        return os.path.join(self, other)
    def __rdiv__(self, other):
        assert isinstance(other, str)
        return os.path.join(other, self)

# Using __div__
print MyPath("/home/bob") / MyPath("bin")
print MyPath("/home/bob") / "bin"

# Using __rdiv__
print "/home/bob" / MyPath("bin")

关于python - python中有对应 "\"的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566883/

相关文章:

python - 在 matplotlib 中使用 basemap 绘制爱尔兰的海岸线

PHP子串删除

python - CMake 中的错误 Python 2 库

python - Python 中的 pickle 和 yaml 之间的基本区别是什么?

python - Tkinter StringVar 错误

python - win32file.ReadDirectoryChangesW找不到所有移动的文件

python - python中的非线性特征变换

python - 如何在 Python 中重定向 stderr?通过 Python C API?

python - 关闭开发服务器上的 Celery 任务延迟

python - 将引号作为 python 列表中的字符