Skip to main content
 首页 » 编程设计

python之str.startswith() 没有按我的预期工作

2025年05月04日8lonelyxmas

我正在尝试测试/t 或空格字符,但我不明白为什么这段代码不起作用。我正在做的是读入一个文件,计算文件的位置,然后记录文件中存在的每个函数的名称以及它们各自的代码行。下面的代码是我尝试计算函数位置的地方。

import re 
 
... 
    else: 
            loc += 1 
            for line in infile: 
                line_t = line.lstrip() 
                if len(line_t) > 0 \ 
                and not line_t.startswith('#') \ 
                and not line_t.startswith('"""'): 
                    if not line.startswith('\s'): 
                        print ('line = ' + repr(line)) 
                        loc += 1 
                        return (loc, name) 
                    else: 
                        loc += 1 
                elif line_t.startswith('"""'): 
                    while True: 
                        if line_t.rstrip().endswith('"""'): 
                            break 
                        line_t = infile.readline().rstrip() 
 
            return(loc,name) 

输出:

Enter the file name: test.txt 
line = '\tloc = 0\n' 
 
There were 19 lines of code in "test.txt" 
 
Function names: 
 
    count_loc -- 2 lines of code 

如您所见,我对该行的测试打印显示了一个/t,但是 if 语句明确指出(或者我认为)它应该只在不存在空白字符的情况下执行。

这是我一直在使用的完整测试文件:

def count_loc(infile): 
    """ Receives a file and then returns the amount 
        of actual lines of code by not counting commented 
        or blank lines """ 
 
    loc = 0 
    for line in infile: 
        line = line.strip() 
        if len(line) > 0 \ 
        and not line.startswith('//') \ 
        and not line.startswith('/*'): 
            loc += 1 
            func_loc, func_name = checkForFunction(line); 
        elif line.startswith('/*'): 
            while True: 
                if line.endswith('*/'): 
                    break 
                line = infile.readline().rstrip() 
 
    return loc 
 
 if __name__ == "__main__": 
    print ("Hi") 
    Function LOC = 15 
    File LOC = 19 

请您参考如下方法:

在进行模式匹配时,

\s 只是 re 包的空白。

对于startswith这种普通字符串的普通方法,\s没有什么特别之处。不是模式,只是字符。