Answers:
该lstrip()方法将删除以字符串开头的前导空格,换行符和制表符:
>>> '     hello world!'.lstrip()
'hello world!'编辑
正如balpha在注释中指出的那样,为了仅从字符串开头删除空格,lstrip(' ')应使用:
>>> '   hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'相关问题:
如果要剪切单词前后的空格,请保留中间的空格。
您可以使用:
word = '  Hello World  '
stripped = word.strip()
print(stripped)'Hello World'有中间空格,对于任何想知道的人,我想它都已被否决,因为最初的问题专门要求删除前导空格。
                    这个问题不会解决多行字符串,但是这是如何使用python的标准库textwrap模块从多行字符串中去除前导空格。如果我们有一个像这样的字符串:
s = """
    line 1 has 4 leading spaces
    line 2 has 4 leading spaces
    line 3 has 4 leading spaces
"""如果我们print(s)得到如下输出:
>>> print(s)
    this has 4 leading spaces 1
    this has 4 leading spaces 2
    this has 4 leading spaces 3如果我们使用了textwrap.dedent:
>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3