刚刚写了这个函数...
def nrofleadingchars(stringtotest, testchar='\t'):
count = 0
for c in stringtotest:
if c == testchar:
count = count + 1
else:
return count
return count
但是感觉 pythonic 还不够,有什么建议吗?
最佳答案
import itertools
def nrofleadingchars(stringtotest, testchar='\t'):
return len(list(itertools.takewhile(lambda x: x == testchar, stringtotest)))
由于需要构建列表,对于前缀非常大的事物,这可能效率较低。如果我可能要处理这样的问题,我可能会这样写:
def num_leading_chars(a_string, prefix='\t'):
for idx, char in enumerate(a_string):
if char != prefix:
return idx
return len(a_string)
关于python - 寻找更多的pythonic方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357655/