[Python] why is my startswith() only returning 0 even though the other methods, using the...

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo


    My beginswith(n_list, sub) function is where the startswith() method is; it is only returning 0. It is the only problem I am having. It is formatted like the working endswith() and .contains() methods, yet it isn't working.
    ​

    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()

    Continue reading...

Compartilhe esta Página