我知道我可以用这个来计算字符串中的前导空格:
>>> 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)
我不确定这段代码是否真的比原始解决方案更好.它的优点是它不会创建更多的临时字符串,但这非常小(除非字符串非常大).我没有发现任何一个版本都能立即明确该代码行,所以如果你计划多次使用它,我肯定会把它包装在一个很好的命名函数中(在任何一种情况下都有适当的注释).
只是为了变化,理论上你可以使用正则表达式.它有点短,看起来比双重呼叫更好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)