我的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()
检查文件中的每个名称是否以特殊的、不可见的字符开头。您还可以向我们提供文件的内容,以便我们进行复制。