Вопрос

I'm trying to write a program which has a function that finds and prints the author of a file by looking for the Author string in the docstring. I've managed to get the code below to print the author of a file that has the author string followed by the authors name and also the author string not followed by a name. The thing I'm having problems with is trying to print Unknown when the author string does not exist at all i.e. no part of the docstring contains Author.

N.B. lines is just a list constructed by using readlines() on a file.

 def author_name(lines):
    '''Finds the authors name within the docstring'''
    for line in lines:
        if line.startswith("Author"):
            line = line.strip('\n')
            line = line.strip('\'')
            author_line = line.split(': ')
            if len(author_line[1]) >=4:   
                print("{0:21}{1}".format("Author", author_line[1])) 
            else:
                print("{0:21}{1}".format("Author", "Unknown"))
Это было полезно?

Решение

If you are writing a function, then return a value. Do not use print (that is for debugging only). Once you use return, you can return early if you do find the author:

def author_name(lines):
    '''Finds the authors name within the docstring'''
    for line in lines:
        name = 'Unknown'
        if line.startswith("Author"):
            line = line.strip('\n')
            line = line.strip('\'')
            author_line = line.split(': ')
            if len(author_line[1]) >=4:   
                name = author_line[1]
            return "{0:21}{1}".format("Author", name)  # ends the function, we found an author

    return "{0:21}{1}".format("Author", name)

print(author_name(some_docstring.splitlines()))

The last return statement only executes if there were no lines starting with Author, because if there was, the function would have returned early.

Alternatively, because we default name to Unknown, you can use break as well to end the loop early and leave returning to that last line:

def author_name(lines):
    '''Finds the authors name within the docstring'''
    for line in lines:
        name = 'Unknown'
        if line.startswith("Author"):
            line = line.strip('\n')
            line = line.strip('\'')
            author_line = line.split(': ')
            if len(author_line[1]) >=4:   
                name = author_line[1]
            break  # ends the `for` loop, we found an author.

    return "{0:21}{1}".format("Author", name)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top