开发者

Python error, " 'module' object has no attribute 'lstrip' "

开发者 https://www.devze.com 2023-02-04 13:26 出处:网络
Python documentation from http://docs.python.org/library/string.html : string.lstrip(s[, chars]) Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace c

Python documentation from http://docs.python.org/library/string.html :

string.lstrip(s[, chars])

Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will 开发者_如何学编程be stripped from the beginning of the string this method is called on."

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'
>>> 

What am I missing here?


Documentation for py3k version is located here: http://docs.python.org/py3k/index.html

string functions were removed in py3k and you have to use now str methods:

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

Note, that as documentation says, chars must be a string. Not an integer.


For Python 2.6 the following works ...

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

For Python 3.0 the previous solution won't work since string.lstrip was deprecated in 2.4 and removed in 3.0.

Another way is to do:

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

or

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

Which I think is the common widely use of it.

Edit

To add deprecation of string.lstrip in Python 3.0 - thanks for the comments on this answer that mentioned it.


You don't look the good doc you are using python 3.1 the right doc is here http://docs.python.org/py3k/library/string.html


This was changed for Python 3.x.

The method you referring to is only available for string instances, not the module string. So you don't need to import anything:

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


You have found the Python 2.7.1 version of the docs (look at the top left corner of the screen). string functions were deprecated in Python 2.x in favour of str and unicode methods, and removed totally in Python 3.x. See the 3.x docs here.

0

精彩评论

暂无评论...
验证码 换一张
取 消