【问题标题】:Are there differences between string.replace / .strip / .find and the built-in functions?string.replace / .strip / .find 和内置函数之间有区别吗?
【发布时间】:2020-02-26 11:59:10
【问题描述】:

我有一个 Python 2 代码库,我正在迁移到 Python 3。旧代码库使用

import string

foo = string.replace(s, old, new)
foo = string.strip(s)
foo = string.find(s, sub, start, end)

我用 2to3 移动了它,但这给出了一个错误。我的猜测是我必须用

替换上面的
foo = s.replace(old, new)
foo = s.strip()
foo = s.find(sub, start, end)

我查看了文档:

它们看起来完全一样。为什么这些函数首先出现在 string 模块中?这是 Python 2.7 之前的变化吗?是否可能存在性能差异或某些特殊情况的不同处理方式?

【问题讨论】:

    标签: python python-3.x python-2.7 python-2to3


    【解决方案1】:

    CPython 2.7 string module source 来看,它们是方法调用的简单包装器。这在更老的 Python 中可能有所不同。来自相同代码的初始 cmets:

    从 Python 1.6 开始,其中许多函数都实现为 标准字符串对象上的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-05
      • 2011-08-31
      • 1970-01-01
      • 2015-08-19
      • 2015-10-03
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      相关资源
      最近更新 更多