Python错误:“模块对象没有'lstrip'属性”
这是Python文档中的内容,来自于http://docs.python.org/library/string.html:
string.lstrip(s[, chars])
这个方法会返回一个新的字符串,去掉开头的字符。如果你没有提供chars这个参数或者它是
None
,那么就会去掉开头的空白字符。如果你提供了chars并且它不是None
,那么chars必须是一个字符串;这个字符串中的字符会被从调用这个方法的字符串的开头去掉。
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'
>>>
我这里漏掉了什么吗?
5 个回答
1
这个在Python 3.x中有了变化。
你提到的方法只适用于字符串实例,而不是string
这个模块。所以你不需要导入任何东西:
assert 'a ' == ' a '.lstrip()
4
对于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
我觉得这是一种比较常见的用法。
编辑
补充说明一下,string.lstrip
在Python 3.0中被标记为不推荐使用,感谢评论中提到这一点的朋友。
8
py3k版本的文档可以在这里找到:http://docs.python.org/py3k/index.html
在py3k中,string
函数被移除了,现在你需要使用str
的方法:
>>> x = 'Hi'
>>> x.lstrip('H')
'i'
注意,文档中提到,chars
必须是一个字符串,而不是一个整数。