Python Script for startswith and endswith

2.3k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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)
2
On

Is this what you're looking for?

def clean(names):
   return [name.strip().lower() for name in names] 

with open("names.txt", "r") as names:
   for name in clean(names):
      if name.startswith('a') and name.endswith('s'):
         print(name)

Keep in mind that startswith and endswith are case sensitive. Adding lower() in this solution makes it case insensitive. You can remove that from the clean() method if you want.

Also, as @ShadowRanger so graciously pointed out, you need to strip the line ending with rstrip (right strip). This solution uses strip(), which also clears any whitespace from the start of the name string, e.g. if there are tabs or spaces, they will be removed.