Search code examples
pythonstartswithends-with

Python Script for startswith and endswith


So I made this script:

names = open("names.txt","r")
for loop in names:
  if loop.endswith('s'):
    print(loop)
for loop in names:
  if loop.startswth('A'):
    print(loop)

There was a file called names.txt which had 10 names in it. This program is supposed to print all the names that start with A and names that end with s but it doesn't work. Can you help me?


Solution

  • You've got a couple problems:

    1. You've got two loops, but the file is exhausted by the first loop so the second loop never runs (it finds names empty and bypasses the body of the loop)
    2. You're testing for endswith('s'), but almost every line would actually end with a newline, which you haven't stripped

    As a minimal fix for both problems (maintaining the behavior of two loops so you print the lines the end with s separately and first):

    with open("names.txt") as names:
        for loop in names:
            loop = loop.rstrip('\n')  # Remove trailing newline, if any, to avoid doubled
                                      # newline on print and make test work
            if loop.endswith('s'):
                print(loop)
        names.seek(0)  # Reset file pointer to beginning of file
        for loop in names:
            loop = loop.rstrip('\n')  # Same strip as in prior loop
            if loop.startswith('A'):
                print(loop)
    

    If any passing line being printed on a single pass is fine, and you don't need lines beginning with A and ending with s to be printed twice, you can simplify to:

    with open("names.txt") as names:
        for loop in names:
            loop = loop.rstrip('\n')  # Remove trailing newline, if any, to avoid doubled
                                      # newline on print and make test work
            if loop.startswith('A') or loop.endswith('s'):
                print(loop)