【问题标题】:Python error, " 'module' object has no attribute 'lstrip' "Python 错误,“‘模块’对象没有属性‘lstrip’”
【发布时间】:2011-01-14 11:06:37
【问题描述】:

来自http://docs.python.org/library/string.html 的 Python 文档:

string.lstrip(s[, chars])

返回删除前导字符的字符串副本。如果chars 被省略或None,空白字符被删除。如果给定而不是Nonechars 必须是字符串;字符串中的字符将从调用此方法的字符串的开头删除。"

Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> import string
>>> x = 'Hi'
>>> string.lstrip(x,1)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    string.lstrip(x,1)
AttributeError: 'module' object has no attribute 'lstrip'
>>> 

我在这里错过了什么?

【问题讨论】:

  • 它应该给你 TypeError 因为 1 不是字符。

标签: python string python-3.x


【解决方案1】:

py3k 版本的文档位于此处:http://docs.python.org/py3k/index.html

string 函数已在 py3k 中删除,您现在必须使用 str methods

>>> x = 'Hi'
>>> x.lstrip('H')
'i'

请注意,正如文档所述,chars 必须 是一个字符串。不是整数。

【讨论】:

  • 自 python 2.5 起不推荐使用字符串模块
  • @Ant: string 模块很好,只是一些功能被弃用了。
【解决方案2】:

对于 Python 2.6,以下工作...

import string
x = u'Hi' #needs to be unicode
string.lstrip(x,'H') #second argument needs to be char

对于 Python 3.0,之前的解决方案将不起作用,因为 string.lstrip 在 2.4 中已被弃用并在 3.0 中被删除。

另一种方法是:

"Hi".lstrip('H')  #strip a specific char

" Hi".lstrip() #white space needs no input param

我认为这是它的普遍广泛使用。

编辑

在 Python 3.0 中添加对 string.lstrip 的弃用 - 感谢 cmets 在这个答案中提到它。

【讨论】:

  • 另外,string.lstrip 不是正确的做法,因为它在 Python 3 中已被弃用
  • 你的意思是我提到了 Python 2.6 吗?还是第一段代码?
  • 对,我不知道它在 3.0 中已被弃用,我会提到 - 谢谢。
  • 它在 py3k 中没有被 not 弃用。它在 2.4 中被弃用,在 py3k 中这些函数根本不存在。
  • @SilentGhost:没错,我的意思是它们根本不存在(不过我似乎无法编辑我的评论)
【解决方案3】:

你看起来不像你使用 python 3.1 的好文档,正确的文档在这里http://docs.python.org/py3k/library/string.html

【讨论】:

  • 不是我,但可能是因为您提供的 URL 指向 string 模块,而不是他需要阅读的 str 方法。
【解决方案4】:

这已针对 Python 3.x 进行了更改。

您所指的方法仅适用于字符串实例,不适用于模块string。所以你不需要导入任何东西:

 assert 'a ' == '  a '.lstrip()

【讨论】:

  • 2.x 中进行了更改,因此您无需导入任何内容。
【解决方案5】:

您已找到文档的 Python 2.7.1 版本(查看屏幕左上角)。 string 函数在 Python 2.x 中被弃用,取而代之的是 strunicode 方法,并在 Python 3.x 中完全删除。请参阅 3.x 文档here

【讨论】:

    猜你喜欢
    • 2011-06-19
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    相关资源
    最近更新 更多