来自http://docs.python.org/library/string.html的Python文档:
string.lstrip(s[, chars])
返回删除了前导字符的字符串副本。如果省略 chars 或
None
,则删除空格字符。如果给定而不是None
,则字符必须是字符串;字符串中的字符将从调用此方法的字符串的开头删除。“
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'
>>>
我在这里缺少什么?
答案 0 :(得分:7)
py3k版本的文档位于:http://docs.python.org/py3k/index.html
在py3k中删除了 string
个函数,您必须立即使用str
methods:
>>> x = 'Hi'
>>> x.lstrip('H')
'i'
请注意,正如文档所述,chars
必须为字符串。不是整数。
答案 1 :(得分:3)
对于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
的弃用 - 感谢对此答案提出的评论。
答案 2 :(得分:1)
您已找到文档的Python 2.7.1版本(请查看屏幕的左上角)。 {2.}}函数在Python 2.x中被弃用,支持string
和str
方法,并完全在Python 3.x中删除。请参阅3.x文档here。
答案 3 :(得分:0)
你看起来不是你使用python 3.1的好文档,正确的文档在这里http://docs.python.org/py3k/library/string.html
答案 4 :(得分:0)
Python 3.x已更改。
您引用的方法仅适用于字符串实例,而不适用于模块string
。所以你不需要导入任何东西:
assert 'a ' == ' a '.lstrip()