我知道我可以用这个来计算字符串的前导空格:
>>> a = " foo bar baz qua \n" >>> print "Leading spaces", len(a) - len(a.lstrip()) Leading spaces 3 >>>
但是有没有更简洁的方法呢?
看起来... 很不错。通常我会回答“是 X Python 吗?”但我觉得这种方法不适合字符串操作。
如果有一个内置的 只有返回的领先空间,并采取的 len()的,我会说去它-但 AFAIK 没有,和 re和其他解决方案是绝对过度杀伤力。
len()
re
你可以用 itertools.takewhile
itertools.takewhile
sum( 1 for _ in itertools.takewhile(str.isspace,a) )
并演示它给出与代码相同的结果:
>>> 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
我不确定这个代码是否实际上是 好多了比您的原始解决方案。它的优点是不会创建更多的临时字符串,但是这个优点相当小(除非字符串真的很大)。我没有发现任何一个版本的代码行能够立即清楚,所以如果您打算多次使用它(在任何一种情况下都使用适当的注释) ,我肯定会将它包装在一个名称很好的函数中。
你的方法是 pythonic 但不正确的,它也会计算其他空格字符,只计算空格是显式的 a.lstrip(' '):
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
使用 next和 enumerate:
next
enumerate
next((i for i, c in enumerate(a) if c != ' '), len(a))
对于任何空格:
next((i for i, c in enumerate(a) if not c.isspace()), len(a))
只是为了多样化,理论上可以使用 regex。短了一点,看起来比 len()的双重呼叫好多了。
>>> import re >>> a = " foo bar baz qua \n" >>> re.search('\S', a).start() # index of the first non-whitespace char 3
或者:
>>> re.search('[^ ]', a).start() # index of the first non-space char 3
但是我不推荐这样做; 根据我做的一个快速测试,它的效率比 len(a)-len(lstrip(a))低得多。
len(a)-len(lstrip(a))
我最近有一个类似的计算缩进的任务,因此我想把 tab 计算为四个空格:
def indent(string: str): return sum(4 if char is '\t' else 1 for char in string[:-len(string.lstrip())])
可以使用正则表达式:
def count_leading_space(s): match = re.search(r"^\s*", s) return 0 if not match else match.end() In [17]: count_leading_space(" asd fjk gl") Out[17]: 4 In [18]: count_leading_space(" asd fjk gl") Out[18]: 1 In [19]: count_leading_space("asd fjk gl") Out[19]: 0