为什么我的startswith()只返回0,即使使用完全相同格式的其他方法正在工作?

问题描述 投票:0回答:1

我的beginswith(n_list, sub)函数就是startswith()方法所在的地方;它只返回 0。这是我遇到的唯一问题。它的格式类似于工作的endswith()和.contains()方法,但它不起作用。

def readFile(file_name):
        try:
            with open(file_name, "r", encoding="utf-8") as file:
                return [line.strip() for line in file]


             
    except FileNotFoundError: 
            print(f"The file name you specified does not exist.") 
            main() 
 
def beginswith(n_list, sub): 
    return sum(names.startswith(sub) for names in n_list) 

def endswith(n_list, sub): 
    return sum(names.endswith(sub) for names in n_list)

def contains(n_list, sub): 
    return sum(names.__contains__(sub) for names in n_list)

def getStats(n_list, sub): #gets stats function
    stats_list = [] #empty list to store values
    stats_list.append(beginswith(n_list, sub)) 
    stats_list.append(endswith(n_list, sub)) 
    stats_list.append(contains(n_list, sub))
    return stats_list 


def main(): 
    file_name = input("What file do you want to open? ")
    n_list = readFile(file_name) 
    print(f"The list has {len(n_list)} names") 
        
    while True: 
            sub = input("What name (or substring) are you interested in searching for? ") 
            
            if not sub:
                   break
    
            begins_with_num = beginswith(n_list, sub) 
            ends_with_num = endswith(n_list, sub) 
            contains_sub_num = contains(n_list, sub) 
            stats_list = getStats(n_list, sub) 
            
            print(f"{begins_with_num} name(s) begin with '{sub}'")
            print(f"{ends_with_num} names(s) ends with '{sub}'")
            print(f"{contains_sub_num} name(s) contain '{sub}'")
            print(stats_list) 

    
# Main portion of code for local testing
if __name__ == "__main__":
       main() 
python
1个回答
0
投票

检查文件中的每个名称是否以特殊的、不可见的字符开头。您还可以向我们提供文件的内容,以便我们进行复制。

© www.soinside.com 2019 - 2024. All rights reserved.