计算字符串中前导空格的pythonic方法是什么?

gri*_*eve 41 python

我知道我可以用这个来计算字符串中的前导空格:

>>> a = "   foo bar baz qua   \n"
>>> print "Leading spaces", len(a) - len(a.lstrip())
Leading spaces 3
>>>
Run Code Online (Sandbox Code Playgroud)

但是有更多的pythonic方式吗?

zen*_*poy 68

你的方式是pythonic但不正确,它也会计算其他空格字符,只计算空格是明确的a.lstrip(' '):

a = "   \r\t\n\tfoo bar baz qua   \n"
print "Leading spaces", len(a) - len(a.lstrip())
>>> Leading spaces 7
print "Leading spaces", len(a) - len(a.lstrip(' '))
>>> Leading spaces 3
Run Code Online (Sandbox Code Playgroud)


mgi*_*son 19

你可以用 itertools.takewhile

sum( 1 for _ in itertools.takewhile(str.isspace,a) )
Run Code Online (Sandbox Code Playgroud)

并证明它提供与您的代码相同的结果:

>>> import itertools
>>> a = "    leading spaces"
>>> print sum( 1 for _ in itertools.takewhile(str.isspace,a) )
4
>>> print "Leading spaces", len(a) - len(a.lstrip())
Leading spaces 4
Run Code Online (Sandbox Code Playgroud)

我不确定这段代码是否真的比原始解决方案更好.它的优点是它不会创建更多的临时字符串,但这非常小(除非字符串非常大).我没有发现任何一个版本都能立即明确该代码行,所以如果你计划多次使用它,我肯定会把它包装在一个很好的命名函数中(在任何一种情况下都有适当的注释).

  • @ChaimG - 这就是为什么:-).有一次,我认为`lstrip()`不会创建一个新字符串 - Immutability _should_使这成为可能.但是,我曾在google邮件列表上发表过一次声明,并由Alex Martelli IIRC更正:-).我不确定为什么他们_don't_重新使用旧字符串,但这可能是因为在很多情况下会阻止大字符串被释放. (3认同)
  • 在我的系统上,(在Windows上运行的Python 2.7.10 32位),lstrip()的速度是itertools的3.5倍. (2认同)

Jun*_*uxx 9

只是为了变化,理论上你可以使用正则表达式.它有点短,看起来比双重呼叫更好len().

>>> import re
>>> a = "   foo bar baz qua   \n"
>>> re.search('\S', a).start() # index of the first non-whitespace char
3
Run Code Online (Sandbox Code Playgroud)

或者:

>>> re.search('[^ ]', a).start() # index of the first non-space char
3
Run Code Online (Sandbox Code Playgroud)

但我不推荐这个; 根据我做的快速测试,它的效率低于len(a)-len(lstrip(a)).


小智 6

我最近有一个类似的计算缩进的任务,因此我想将制表符计算为四个空格:

def indent(string: str):
    return sum(4 if char is '\t' else 1 for char in string[:-len(string.lstrip())])
Run Code Online (Sandbox Code Playgroud)