查找在Python中开始字符串的空格数的最快方法是什么?

时间:2018-01-27 05:31:32

标签: python text-parsing

找到开始字符串的空格数的最快方法是什么?我想要这个来计算嵌套我的空间缩进的方式(当文本解析时)。

E.g。

s="     There are five spaces"
num=num_start_spaces(s) #it equals five

我可能不会问这个,但我注意到我没有在任何地方找到它的快速参考(所以,我以为我会做我自己的Q / A;如果你有另一种方式,请随意贡献!)。

2 个答案:

答案 0 :(得分:2)

这是一个替代答案:

def countspaces(x):
    for i, j in enumerate(x):
        if j != ' ':
            return i

s="     There are five spaces"

countspaces(s)  # 5

答案 1 :(得分:1)

可以使用str.lstrip()方法并获取两个字符串长度的差异,这将是开始字符串的空格数。

def num_start_spaces(text):
    return len(text)-len(text.lstrip(" "))

print(num_start_spaces("        spaces"))

以上打印“8个空格”。

编辑:我使用重复问题中的信息增强了上述答案。

然而,对于手头的任务,我认为在所述的上下文中单独执行此操作将会有点单调乏味并且有很多开销。在进行任何文本解析之前,您可能希望使用它来制作每行的缩进列表(然后当您遍历这些行时,您将有这些用于快速参考):

lines=myString.split("\n") #lines is the lines of the text we're parsing
indents=[] #Values are the number of indents on the line.
for line in lines:
    spaces=num_start_spaces(line)
    if spaces%4!=0:
        raise ValueError("The spaces on line "+str(len(indents))+" are not zero or a multiple of four:", spaces)
    indents.append(spaces/4)

i=0
while i<len(lines):
    #Do text parsing here (and use indents for reference). We're in a while loop so we can reference lines before and after more easily than in a for loop.
    i+=1
相关问题